這是最多見的,建立一個thread,而後讓它在while循環裏一直運行着,經過sleep方法來達到定時任務的效果。這樣能夠快速簡單的實現,代碼以下:java
public class Task1 { public static void main(String[] args) { // run in a second final long timeInterval = 1000; Runnable runnable = new Runnable() { public void run() { while (true) { // ------- code for task to run System.out.println("Hello !!"); // ------- ends here try { Thread.sleep(timeInterval); } catch (InterruptedException e) { e.printStackTrace(); } } } }; Thread thread = new Thread(runnable); thread.start(); } }
上面的實現是很是快速簡便的,但它也缺乏一些功能。
用Timer和TimerTask的話與上述方法相比有以下好處:安全
在實現時,Timer類能夠調度任務,TimerTask則是經過在run()方法裏實現具體任務。
Timer實例能夠調度多任務,它是線程安全的。
當Timer的構造器被調用時,它建立了一個線程,這個線程能夠用來調度任務:併發
import java.util.Timer; import java.util.TimerTask; public class Task2 { public static void main(String[] args) { TimerTask task = new TimerTask() { @Override public void run() { // task to run goes here System.out.println("Hello !!!"); } }; Timer timer = new Timer(); long delay = 0; long intevalPeriod = 1 * 1000; // schedules the task to be run in an interval timer.scheduleAtFixedRate(task, delay, intevalPeriod); } // end of main }
ScheduledExecutorService是從Java SE 5的java.util.concurrent裏,作爲併發工具類被引進的,這是最理想的定時任務實現方式。
相比於上兩個方法,它有如下好處:ide
咱們經過ScheduledExecutorService#scheduleAtFixedRate展現這個例子,經過代碼裏參數的控制,首次執行加了delay時間:工具
import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class Task3 { public static void main(String[] args) { Runnable runnable = new Runnable() { public void run() { // task to run goes here System.out.println("Hello !!"); } }; ScheduledExecutorService service = Executors .newSingleThreadScheduledExecutor(); service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS); } }