任務調度(三)——Timer的替代品ScheduledExecutorService簡介,scheduledexecutor

來源:互聯網
上載者:User

任務調度(三)——Timer的替代品ScheduledExecutorService簡介,scheduledexecutor

       先前的兩篇博文《任務調度(一)——jdk內建的Timer》和《任務調度(二)——jdk內建的Timer 動態修改任務執行計畫》中,簡單介紹了一下Timer,可以實現幾本的功能,但是在多線程方面卻略顯不足。


       根據Timer源碼,可以看到Timer是單線程的。所以task都是串列執行。假如其中一個task執行需要很長的時間,那其他的task只能乾巴巴的等著。怎麼辦!


      現在就遇到了這樣的問題。總不能因為這個小小的問題就去換別的任務調度架構吧,還是想用最簡單的方案去解決一下。所以ScheduledExecutorService就被我選中了。這個是怎麼找到的?1.網上搜,2.好好的看Timer類的注釋:


       翻譯一下:java5.0引入了java.util.concurrent包,其中java.util.concurrent.scheduledthreadpoolexecutor就是在並發工具 + 生產力其中之一。scheduledthreadpoolexecutor是一個可以重複執行任務的線程池,並且可以指定任務的間隔和延遲時間。它作為比Timer/TimerTask更加通用的替代品。因為它允許多個服務線程,接受不同的時間單位,且不需要繼承TimeTask(僅僅需要實現Runnable介面)。配置ScheduledThreadPoolExecutor為單線程,則與使用Timer等效。


       ScheduledThreadPoolExecutor實現了ScheduledExecutorService介面,所以標題中使用了介面的名字。

       ScheduledExecutorService提供了4個方法:


       其中第二個方法比較特殊一點,第一個參數是Callable,別的都是Runnable,二者的區別不再這篇博文的討論範圍之內。就此略過。說一些其他三個方法。

       schedule()方法第一個參數是任務執行個體,第二個參數是延遲時間,第三個是時間單元。比如調用如下:

ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);pool.schedule(task1, 5, TimeUnit.SECONDS);//延遲5s後,執行且只執行一次task1

       scheduleAtFixedRate()和scheduleWithFixedDelay方法參數是一樣的。第一個參數是任務執行個體,第二個參數是延遲時間,第三個是間隔時間,第四個是時間單元。這兩個方法的不同之處在方法名也能看得出來:scheduleAtFixedRate方法是按照固定頻率去執行任務的。而scheduleWithFixedDelay方法則是按照固定的延遲去執行任務。

/**  * task1 *  * @author arron * @date 2015年8月5日 下午2:08:34  * @version 1.0  */public class Task1 implements Runnable{@SuppressWarnings("deprecation")public void run() {System.out.println("----task1 start--------"+new Date().toLocaleString());try {Thread.sleep(3000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("----3s later, task1 end--------"+new Date().toLocaleString());}}
測試scheduleAtFixedRate方法:
public static void main(String[] args) {ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);Task1 t1 = new Task1();//立即執行t1,3s後任務結束,再等待2s(間隔時間-消耗時間),如果有空餘線程時,再次執行該任務pool.scheduleAtFixedRate(t1, 0, 5, TimeUnit.SECONDS);}
       執行結果

       task1第二次執行的前提是,當前有空餘的線程。

       執行的開始時間則是上一次結束時間+(間隔時間-任務消耗的時間)。加入這個差值小於0,即間隔時間小於任務消耗的時間,那就不會再等待,會立即執行(當然得滿足前提)。


測試scheduleAtFixedRate方法:

public static void main(String[] args) {ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);Task1 t1 = new Task1();//立即執行t1,3s後任務結束,再等待5s(間隔時間-消耗時間),如果有空餘線程時,再次執行該任務pool.scheduleWithFixedDelay(t1, 0, 5, TimeUnit.SECONDS);}
       執行結果


       就簡單介紹到這裡,下篇將會分享替換Timer的代碼。


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.