创建ScheduleThreadPool
ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(5);
这里还是选择自动创建的,参数是 corePoolSize即5个,下面看怎么自动创建
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
从源码可以看出,它创建线程池,是调用了父类的构造方法,如下
public class ScheduledThreadPoolExecutor
extends ThreadPoolExecutor
implements ScheduledExecutorService
继承了 ThreadPoolExecutor,所以创建 ScheduledThreadExecutor 本质也是创建一个 ThreadPoolExecutor 线程池,只是传入的参数不相同,那么 ScheduledThreadExecutor 的方法传入了哪些参数?
- 第一个参数位置,是 corePoolSIze,也就是5个核心线程数
- 第二个参数位置,是 maximumPoolSize,也就是Integer.MAX_VALUE,代表了理论可以创建的线程最大的个数
- 第三个参数位置,是KeepAliveTime,也就是空闲线程存活的时间,既然是零,也就是线程池空闲的时候,会把线程直接销毁
- 第四个参数位置,是 unit,居然是NANOSECONDS,反正是前面的 KeepAliveTime是0了, 是纳秒还是毫秒,好像差不多的样子
- 第五个参数位置,是 Handler,是DelayedWorkQueue,一个延迟队列,也就是按一定的时间执行任务,或者每隔一段时间执行一次任务
ScheduleThreadPool的使用
ScheduledThreadPool.shedule(Runnable command,long delay, TimeUnit unit)
public class TestScheduledThreadPool {
public static void main(String[] args) {
ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(5);
Thread thread = new Thread(new Runnable() {
@Override
public void run