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