1. 程式人生 > 其它 >定時執行緒池ScheduledThreadPoolExecutor

定時執行緒池ScheduledThreadPoolExecutor

技術標籤:筆記併發專題

繼承圖

Timer和ScheduledThreadPoolExecutor的區別

Timer內部只維護了一個執行緒,如果執行緒掛了不會恢復。

ScheduledThreadPoolExecutor內部是一個執行緒池,如果執行緒掛了會在建立新的執行緒執行完成後面的任務。

ScheduledThreadPoolExecutor特性

public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize, Integer.MAX_VALUE,DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,new DelayedWorkQueue());
}
ScheduledThreadPoolExecutor使用的是DelayedWorkQueue這個佇列,而這個佇列是基於堆(min heap)結構實現的。會根據執行時間排序,執行時間距離當前時間越近則會排在最前。

方法特性

public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,long initialDelay, long period,TimeUnit unit);
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) 

scheduleAtFixedRate方法工作方式,會線上程啟動initialDelay後將任務新增到佇列中,隨後每隔period給任務佇列提交此任務達到週期效果。此方法如果任務處理時間大於period,隨著時間後移,會很容易存在則大量任務的堆積。而scheduleWithFixedDelay則不會存在則這個問題,scheduleWithFixedDelay方法會當任務執行完成後,會在任務執行完的基礎上延時delay,在提交此任務。