上一节介绍了java线程池ThreadPoolExecutor类,这节介绍周期性线程池ScheduledThreadPoolExecutor类。
1、ScheduledThreadPoolExecutor类图
从类图可以看出ScheduledThreadPoolExecutor类继承了ThreadPoolExector类,就是说ScheduledThreadPoolExecutor拥有execute()和submit()提交异步任务的基础功能,同时实现了一个新接口:ScheduledExecutorService,ScheduledExecutorService接口继承的是ExecutorService接口,下面我们看看ScheduledExecutorService接口里有哪些方法:
其中schedule方法是用来执行线程任务的,接收Runnable类型和Callable类型的任务;scheduleAtFixRate和scheduleWithFixedDelay方法是用来执行周期性任务和周期性延迟任务的,具体在下面会介绍。
2、ScheduledThreadPoolExecutor类详细介绍
2.1 构造函数
源码如下:
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
};
public ScheduledThreadPoolExecutor(int corePoolSize,
ThreadFactory threadFactory) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue(), threadFactory);
};
public ScheduledThreadPoolExecutor(int corePoolSize,
RejectedExecutionHandler handler) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue(), handler);
};
public ScheduledThreadPoolExecutor(int corePoolSize,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
s