Timer跟ScheduledThreadPoolExecutor的區別

Timer的主要方法有:
// 安排在指定的時間執行
void schedule(TimerTask task, Date time)
// 安排在指定的時間開始以重複的延時執行
void schedule(TimerTask task, Date firstTime, long period)
// 安排在指定的延遲後執行
void schedule(TimerTask task, long delay)
// 安排在指定的延遲後開始以重複的延時執行
void schedule(TimerTask task, long delay, long period)
// 安排在指定的時間開始以重複的速率執行
void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
// 安排在指定的延遲後開始以重複的速率執行
void scheduleAtFixedRate(TimerTask task, long delay, long period)
注:重複的延時和重複的速率的區別在於,前者是在前一個任務的執行結束後間隔period時間再開始下一次執行;而scheduleAtFixedRate則是會盡量按照任務的初始時間來按照間隔period時間執行。如果一次任務執行由於某些原因被延遲了,用schedule()調度的後續任務同樣也會被延遲,而用scheduleAtFixedRate()則會快速的開始兩次或者多次執行,是後續任務的執行時間能夠趕上來。

ScheduledThreadPoolExecutor的主要方法:
// 在指定的延遲後執行
<V>ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit)
// 在指定的延遲後執行
ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit)
// 在指定的延遲後以固定速率執行(類似Timer.scheduleAtFixedRate())
ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
// 在指定的延遲後以固定間隔執行(類似Timer.schedule())
ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)

比較:
·Timer對調度的支持是基於絕對時間的,因此任務對系統時間的改變是敏感的;而ScheduledThreadPoolExecutor支持相對時間。
·Timer使用單線程方式來執行所有的TimerTask,如果某個TimerTask很耗時則會影響到其他TimerTask的執行;而ScheduledThreadPoolExecutor則可以構造一個固定大小的線程池來執行任務。
·Timer不會捕獲由TimerTask拋出的未檢查異常,故當有異常拋出時,Timer會終止,導致未執行完的TimerTask不再執行,新的TimerTask也不能被調度;ScheduledThreadPoolExecutor對這個問題進行了妥善的處理,不會影響其他任務的執行。

結論:
Timer有這麼多的缺點,如果是使用JDK1.5以上的話,應該沒什麼理由要使用Timer來進行調度把:)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章