這是最常見(jiàn)的,創(chuàng)建一個(gè)thread,然后讓它在while循環(huán)里一直運(yùn)行著,通過(guò)sleep方法來(lái)達(dá)到定時(shí)任務(wù)的效果。這樣可以快速簡(jiǎn)單的實(shí)現(xiàn),代碼如下:
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.用Timer和TimerTask上面的實(shí)現(xiàn)是非常快速簡(jiǎn)便的,但它也缺少一些功能。用Timer和TimerTask的話與上述方法相比有如下好處:
- 當(dāng)啟動(dòng)和去取消任務(wù)時(shí)可以控制
- 第一次執(zhí)行任務(wù)時(shí)可以指定你想要的delay時(shí)間
在實(shí)現(xiàn)時(shí),Timer類(lèi)可以調(diào)度任務(wù),TimerTask則是通過(guò)在run()方法里實(shí)現(xiàn)具體任務(wù)。Timer實(shí)例可以調(diào)度多任務(wù),它是線程安全的。當(dāng)Timer的構(gòu)造器被調(diào)用時(shí),它創(chuàng)建了一個(gè)線程,這個(gè)線程可以用來(lái)調(diào)度任務(wù):
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}ScheduledExecutorServiceScheduledExecutorService是從Java SE 5的java.util.concurrent里,做為并發(fā)工具類(lèi)被引進(jìn)的,這是最理想的定時(shí)任務(wù)實(shí)現(xiàn)方式。相比于上兩個(gè)方法,它有以下好處:
- 相比于Timer的單線程,它是通過(guò)線程池的方式來(lái)執(zhí)行任務(wù)的
- 可以很靈活的去設(shè)定第一次執(zhí)行任務(wù)delay時(shí)間
- 提供了良好的約定,以便設(shè)定執(zhí)行的時(shí)間間隔
我們通過(guò)ScheduledExecutorService#scheduleAtFixedRate展示這個(gè)例子,通過(guò)代碼里參數(shù)的控制,首次執(zhí)行加了delay時(shí)間:
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); }}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注