Java线程池ThreadPoolExecutor的七大参数
源码如下
/**
1. corePoolSize – the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
2. maximumPoolSize – the maximum number of threads to allow in the pool
3. keepAliveTime – when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating.
4. unit – the time unit for the keepAliveTime argument
5. workQueue – the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.
6. threadFactory – the factory to use when the executor creates a new thread
7. handler – the handler to use when execution is blocked because the thread bounds and queue capacities are reached
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), handler);
}
1.corePoolSize
核心线程数: 线程池创建好以后就存在的线程数量,等待异步任务去执行,只要线程池存在,核心线程就会一直存在
/**
* If false (default), core threads stay alive even when idle.
* If true, core threads use keepAliveTime to time out waiting for work.
* 如果为false(默认),核心线程即使在空闲时也保持活动
* 如果为true,核心线程使用keepAliveTime超时等待工作
*/
private volatile boolean allowCoreThreadTimeOut;
// 可以通过该方法设置核心线程超时被回收
threadPoolExecutor.allowCoreThreadTimeOut(true);
2.maximumPoolSize
最大线程池数量: 线程池中允许的最大线程数量,包括核心线程和额外创建的线程数量,当核心线程和阻塞队列都满载时,才会创建新的线程,数量不会超过maximumPoolSize
3.keepAliveTime
存活时间: 有线程处于空闲状态,并且当前线程数量大于corePoolSize,那么空闲的线程就会被回收,回收时间由keepAliveTime决定,回收的线程(maximumPoolSize - corePoolSize)
4.unit
线程空闲时间单位
- NANOSECONDS 纳秒
- MILLISECONDS 毫秒
- SECONDS 秒
- MINUTES 分
- HOURS 时
- DAYS 天
5.workQueue
阻塞队列: 超过核心线程数的任务,会被添加倒阻塞队列中
例如corePoolSize为5,workQueue为10,当任务数量超过5个的时候,新的任务会被添加到workQueue中,workQueue最大的任务数量是10
- LinkedBlockingQueue:一个基于链表结构的可选有界阻塞队列,按照先进先出的顺序进行任务调度。如果不指定容量大小,则默认为 Integer.MAX_VALUE,maximumPoolSize则很难使用到
- PriorityBlockingQueue:一个基于优先级的无界阻塞队列,可以按照自定义的顺序执行任务。
- SynchronousQueue:一个不存储元素的阻塞队列,每个插入操作必须等待另一个线程的移除操作。在这种队列中,每个插入操作都会阻塞,直到有其他线程来获取数据。
- ArrayBlockingQueue:一个基于数组结构的有界阻塞队列,按照先进先出(FIFO)的顺序进行任务调度。
6.threadFactory
线程工厂: 用来创建线程工厂的类,可以设置线程的名称、优先级等
7.handler
拒绝策略: workQueue已满,并且当前线程数已经达到maximumPoolSize,线程池会根据指定的策略拒绝新的任务
- AbortPolicy:默认该策略,直接拒绝新任务,抛出 RejectedExecutionException 异常
- CallerRunsPolicy:将任务回退到调用者所在线程中执行,也就是由调用线程的 run 方法
- DiscardPolicy:直接丢弃无法处理的任务,不会抛出异常
- DiscardOldestPolicy:丢弃添加到工作队列最早的任务,提交当前任务。
工作流程
1.线程池创建完之后,准备好corePoolSize
数量的核心线程,等待执行任务
2.corePoolSize
满了之后,新进来的任务会添加到workQueue
中,空闲状态的corePool
会从workQueue
中获取任务并执行
3.workQueue
满了之后,且corePool
都处于非空闲状态,会开启新的线程执行任务,最大线程数不超过maximumPoolSize
4.workQueue
满了之后,且当前线程数量达到maximumPoolSize
,并且都处于非空闲状态,会执行指定的handler
拒绝新的任务
5.当有线程处于空闲状态,且workQueue
中没有任务、当前线程数量大于corePoolSize
,空闲的线程会等待指定时间keepAliveTime
和指定时间单位unit
后,就会被回收,