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实例

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