任務調度(四)——ScheduledExecutorService替代Timer,實現多線程任務調度,scheduledexecutor

來源:互聯網
上載者:User

任務調度(四)——ScheduledExecutorService替代Timer,實現多線程任務調度,scheduledexecutor

       上篇博文《任務調度(三)——Timer的替代品ScheduledExecutorService簡介》已經對ScheduledExecutorService做了簡單介紹,其實使用ScheduledExecutorService來替代Timer也是迫不得已的事情。主要原因如下:

       第一個問題,隨著業務資料的猛增,我們生產上有幾個任務現在每次執行需要1-3個小時,在這段時間內,該timer下的其他任務只能等待,這是讓人無法忍受的。重開一個Timer?難道要為所有的耗時的Task都單開一個Timer,顯然是不太可能,這樣就太亂了。


       第二個問題,是極其致命的。好多業務資料都是晚上的定時任務跑出來的,結果由於程式的問題或者記憶體資源不足,導致線程被kill了。該timer下的所有任務都未執行,結果第二天整整忙活了一天,主要任務就是——跑任務,調整資料。深受其害呀!


       為了彌補Timer的缺陷,jdk1.5中引入了並發包,這裡面提供的ScheduledExecutorService。具體實作類別是:ScheduledThreadPoolExecutor。ScheduledThreadPoolExecutor支援多線程,同時線上程中對異常進行了捕獲。所以是Timer的完美替換者。


       分享一個執行個體吧:

/**  * task2 * @author arron * @date 2015年8月5日 下午2:08:34  * @version 1.0  */public class Task2 extends TimerTask{@SuppressWarnings("deprecation")@Overridepublic void run() {System.out.println("----task2 start--------"+new Date().toLocaleString());try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("----5s later, task2 end--------"+new Date().toLocaleString());}}
       測試代碼:
public static void main(String[] args) {ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);//啟用2個線程Task1 t1 = new Task1();// 立即執行,任務消耗3秒,執行結束後等待2秒,【有空餘線程時】,再次執行該任務pool.scheduleWithFixedDelay(t1, 0, 2, TimeUnit.SECONDS);// 立即執行,任務消耗5秒,執行結束後等待2秒,【有空餘線程時】,再次執行該任務Task2 t2 = new Task2();pool.scheduleWithFixedDelay(t2, 0, 2, TimeUnit.SECONDS);}
       執行結果



       這樣任務之間就不會相互影響了,而且可以同時執行。但是線程數量要設定好了。過渡增加線程數也會適得其反。

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

聯繫我們

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