線程定時執行的兩種實現方法,線程執行實現

來源:互聯網
上載者:User

線程定時執行的兩種實現方法,線程執行實現

package test;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.Timer;public class TimerTest {public static void main(String[] args){     long now = System.currentTimeMillis();SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 設定日期格式System.out.println("當前系統時間:" + df.format(new Date()));// new Date()為擷取當前系統時間        System.out.println("當前系統時間2: " + transferLongToDate("yyyy-MM-dd HH:mm:ss", now));                Calendar calendar = Calendar.getInstance();        calendar.set(Calendar.HOUR_OF_DAY, 9);        calendar.set(Calendar.MINUTE, 55);        calendar.set(Calendar.SECOND, 0);        long specTime = calendar.getTimeInMillis();        
    //方法一: 使用線程的sleep方法,讓線程休眠來達到按時執行的效果 MyThread thread = new MyThread(); try {Thread.sleep(specTime - now);thread.start();} catch (InterruptedException e) {e.printStackTrace();}
    //方法二: 使用timer.schedule來實現定時執行線程,參數按如下方法執行即可 /*Timer timer = new Timer(); timer.schedule(new MyTask(), specTime - now, 2000);//在1秒後執行此任務,每次間隔2秒執行一次,如果傳遞一個Data參數,就可以在某個固定的時間執行這個任務. */ } // 使用內部類,來實現線程執行後,每隔兩秒繼續執行一次static class MyThread extends Thread{public void run(){System.out.println("________"); MyThread thread = new MyThread();try {Thread.sleep(2000);thread.start();} catch (InterruptedException e) {e.printStackTrace();}}} //使用內部類,利用TimerTask來實現線程的定時執行 static class MyTimerTask extends java.util.TimerTask{ public void run(){ System.out.println("________"); } } /** * 把毫秒轉化成日期 * @param dateFormat(日期格式,例如:MM/ dd/yyyy HH:mm:ss) * @param millSec(毫秒數) * @return */ public static String transferLongToDate ( String dateFormat, long millSec ) { SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); Date date = new Date(millSec); return sdf.format(date); }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.