Spring集成Quartz--ScheduleThreadPool詳解

1.簡介

關於ScheduledThreadPoolExecutor大致特性,JDK1.8中是這麼介紹的。

A ThreadPoolExecutor that can additionally schedule
commands to run after a given delay, or to execute
periodically. This class is preferable to {@link java.util.Timer}
when multiple worker threads are needed, or when the additional
flexibility or capabilities of {@link ThreadPoolExecutor} (which
this class extends) are required.

首先,ScheduledThreadPoolExecutor的本質還是一個線程池,只是在線程池的基礎之上,對用戶提交的任務做了更加靈活的處理:
  a)能夠在指定時間之後執行用戶提交的任務(定時處理)
  b)能夠週期性的執行用戶提交的任務
  c)當在多線程環境下時,ScheduledThreadPoolExecutor優於Timer。
  
而熟悉線程池的人都知道,線程池內部需要一個任務阻塞隊列來協助線程池中任務的有序運行。而在ScheduledThreadPoolExecutor中,應用了DelayWorkQueue延時隊列,來實現對任務的定時執行,並進行排序。JDK1.8 中介紹如下。

Using a custom queue (DelayedWorkQueue), a variant of unbounded DelayQueue. The lack of capacity constraint and the fact that corePoolSize and maximumPoolSize are effectively identical simplifies some execution mechanics (see delayedExecute) compared to ThreadPoolExecutor.

首先,ScheduleThreadPool中使用了自定義的隊列——DelayWorkQueue,一個無界的延時隊列來維護用戶或者應用系統提交的任務。相比於ThreadPoolExecutor,ScheduleThreadPool採用了無界隊列,對隊列容量的大小失去了約束,使得參數corePoolSize 和maximumPoolSize 在數值上保持一致(即使設置了maxmumPoolSize也沒有意義。)

2 ScheduleThreadPool類繼承結構
類結構
從上圖可以看出 ,ScheduleThreadPool 繼承自ThreadPoolExecutor,並實現了ScheduledExecutorService接口。
ThreadPoolExecutor的相關介紹請參考ThreadPoolExecutor線程池詳解
而其ScheduledExecutorService接口聲明如下:

public interface ScheduledExecutorService extends ExecutorService {
     public ScheduledFuture<?> schedule(Runnable command,long delay, TimeUnit unit);

    public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit);

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

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

}

ScheduledExecutorService中聲明瞭四個方法,主要是爲了實現對提交的任務進行週期性的執行功能。
  1. schedule(Runnable command,long delay, TimeUnit unit); 若調用此接口,提交的任務將從現在起,經過delay時間段(unit爲時間單位)後執行。
  2. schedule(Callable callable,long delay, TimeUnit unit);其功能與1一樣,只是參數有所不同,允許傳入callable類型參數,並返回計算結果供後續使用。
  3. scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit);表示傳入的任務,將按照固定的時間週期執行。
  4. scheduleWithFixedDelay(Runnable command,long initialDelay,long delay,TimeUnit unit);類似於3,此處不再介紹。
3. ScheduleThreadPool關鍵特性
  3.1 任務阻塞隊列–DelayQueue
  
  
  3.2 週期任務–ScheduleFutureTask
  
  3.3 ScheduleThreadPool核心方法–submit()與execute()
4 ScheduleThreadPool其他特性
5 ScheduleThreadPool實例

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章