概述
概述线程池构造方法中的参数含义、以及常见的设置线程池参数的办法。
参数含义
ThreadPoolExecutor 总共包含 4 个构造方法,最终调用的是以下方法,参数含义如下:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
corePoolSize
核心线程数,当线程数小于核心线程数时,线程池优先通过创建核心线程去处理任务
默认情况下,核心线程会一直存活,若设置了 allowsCoreThreadTimeOut = true,那么核心线程数在空闲时也会被回收。
maximumPoolSize
最大的线程数,当线程数 >= corePoolSize,并且任务队列满时。线程池会创建新的线程去处理任务。
当总线程数 = maximumPoolSize 时,若任务队列满,对于后续加入的任务,线程池会执行 RejectedExecutionHandler 拒绝策略
keepAliveTime,TimeUnit
keepAliveTime 表示线程最大空闲时间,即线程超过 keepAliveTime 没有任务处理时,线程池会对空闲的线程进行回收,直到线程数 = corePoolSize
若设置了 allowsCoreThreadTimeOut = true,那么核心线程超过空闲时间时也会被回收。
TimeUnit 表示时间的单位,可以为 天、小时、分钟、秒,主要配合 keepAliveTime 使用
workQueue
阻塞的任务队列,当正在工作的线程数 = corePoolSize 时,后续的任务会先加入到任务队列中,后续由线程池进行调度处理。
常用的任务队列根据 有界与无界、阻塞与非阻塞分为以下几种:
threadFactory
创建线程的工厂,可以通过实现 ThreadFactory 接口的方式,去构造线程,设定自定义的线程名称,优先级等。
当不指定 threadFactory 实现时,线程池会默认使用 Executors.defaultThreadFactory() 作为创建线程,创建的线程名称默认为 pool-xxx-thread-,非守护线程、默认优先级。
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), handler);
public class Executors {
static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
DefaultThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
RejectedExecutionHandler
任务拒绝策略,当任务队列满并且正在工作的线程数已经达到 maximumPoolSize 时,线程池已经没有能力去处理新的任务,此时需要执行相应的任务拒绝策略。
AbortPolicy 是默认的拒绝策略
静态工厂方法
Executors 类提供几个静态的创建线程池的办法
// coreSize 和 maximumPoolSize 一样,使用无界阻塞队列
// 没有任务执行时,不会销毁核心线程,占用一定系统资源
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
// 单个线程,使用无界阻塞队列
// 保证任务提交顺序与执行顺序相同
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
// 没有核心线程,放到同步队列中,请求量较大时,创建较多线程
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
// 延时队列
public ScheduledThreadPoolExecutor(int corePoolSize,
ThreadFactory threadFactory) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue(), threadFactory);
// 1.8 之后加入,
public static ExecutorService newWorkStealingPool(int parallelism) {
return new ForkJoinPool
(parallelism,
ForkJoinPool.defaultForkJoinWorkerThreadFactory,
null, true);
}
如何设置合理的线程池参数?
corePoolSize 选择
根据任务属于 CPU 密集型还是 IO 密集型确定 corePoolSize
CPU 密集型任务表示需要大量计算的场景,通常设置 corePoolSize = 物理机 CPU 核数 + 1;线程设置过多可能引发线程上下文频繁切换,所以接近物理机 CPU 核心数即可。
-
为什么 + 1 ? 避免某个线程由于某些原因中断暂停,而浪费 CPU 时钟周期。
IO 密集型任务表示程序对硬盘、内存读写比较频繁的场景,此时 CPU 占用率比较低,一般设置 corePoolSize = 物理机 CPU 核心数 * 2
workQueue 选择
无界队列,即队列的长度没有限制,当使用无界队列时,任务的拒绝策略也就失效了,并且随着任务的累计,服务会有 OOM 的危险,所以
谨慎使用
,LinkedBlockingQueue 是常用的无界队列。
有界队列,有界队列初始化时需要指定长度,能够有效避免资源耗尽的情况,其中 ArrayBlockingQueue 和 PriorityBlockingQueue 都是有界阻塞队列, ArrayBlockingQueue 满足 FIFO 先进先出原则;PriorityBlockingQueue 里面的元素根据任务的优先级进行排序
同步移交队列,SynchronousQueue 是一个不存储元素的阻塞队列,他必须等待被添加的元素被消费之后才能继续添加元素。一般情况下,它要求 maximumPoolSize = Integer.MAX_VALUE,这样线程池就会创建新的线程去处理任务。
RejectedExecutionHandler 选择
若任务不太重要可以抛弃时,那么建议使用 DiscardPolicy、DiscardOldestPolicy 策略
这个参数的设定尽量使用默认值,因为线程池出现拒绝策略的情况,一般可以通过设置前面的参数来避免。