- 常用多线程池
ExecutorService executor01 = newScheduledThreadPool(2);
- 使用方式及参数配置详解
/**
* Creates a thread pool that can schedule commands to run after a
* given delay, or to execute periodically.
* @param corePoolSize the number of threads to keep in the pool,
* even if they are idle
* @return a newly created scheduled thread pool
* @throws IllegalArgumentException if {@code corePoolSize < 0}
*/
/**
* 创建一个线程池,可以调度命令在
* 给定的延迟,或定期执行。
* 设置线程池中的线程数。即使他们是空闲的
* @返回新创建的调度线程池如果{@code corePoolSize < 0}将抛出IllegalArgumentException
*/
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
从源码可以看出,它创建线程池,是调用了父类的构造方法
-
第一个参数位置,是 corePoolSIze,也就是5个核心线程数
-
第二个参数位置,是 maximumPoolSize,也就是Integer.MAX_VALUE,代表了理论可以创建的线程最大的个数
-
第三个参数位置,是KeepAliveTime,也就是空闲线程存活的时间,既然是零,也就是线程池空闲的时候,会把线程直接销毁
-
第四个参数位置,是 unit,居然是NANOSECONDS,反正是前面的 KeepAliveTime是0了, 是纳秒还是毫秒,好像差不多的样子
-
第五个参数位置,是 Handler,是DelayedWorkQueue,一个延迟队列,也就是按一定的时间执行任务,或者每隔一段时间执行一次任务
-
特点
1. 延时启动 、定时启动 、可以自定义最大[线程池]数量
2. 创建一个大小无限的线程池。此线程池支持定时以及周期性执行任务的需求
使用方式:
- 延时运行举例
2. 周期运行举例