线程池组成
创建线程池
创建线程池通过Executors
的工厂方法来创建线程池实例。
实际上Executors
创建的线程池实例最终都是通过实例化配置不同参数的ThreadPoolExecutor
对象。
public static ExecutorService newFixedThreadPool(int nThreads) {return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());}
线程池的参数
下面详细讲解ThreadPoolExecutor
的核心配置参数
/*** Creates a new {@code ThreadPoolExecutor} with the given initial* parameters.** @param corePoolSize the number of threads to keep in the pool, even* if they are idle, unless {@code allowCoreThreadTimeOut} is set* @param maximumPoolSize the maximum number of threads to allow in the* pool* @param 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.* @param unit the time unit for the {@code keepAliveTime} argument* @param workQueue the queue to use for holding tasks before they are* executed. This queue will hold only the {@code Runnable}* tasks submitted by the {@code execute} method.* @param threadFactory the factory to use when the executor* creates a new thread* @param handler the handler to use when execution is blocked* because the thread bounds and queue capacities are reached* @throws IllegalArgumentException if one of the following holds:<br>* {@code corePoolSize < 0}<br>* {@code keepAliveTime < 0}<br>* {@code maximumPoolSize <= 0}<br>* {@code maximumPoolSize < corePoolSize}* @throws NullPointerException if {@code workQueue}* or {@code threadFactory} or {@code handler} is null*/public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler) {...}
int corePoolSize
核心线程数量,线程池将长期保证这些线程处于存活状态,即使线程已经处于闲置状态。除非配置了allowCoreThreadTimeOut
将不会保证长期存活于线程池内,在闲置超过keepAliveTime
后被销毁。
int maximumPoolSize
线程池内的最大数量,线程池内维护的线程不得超过该数量,大于核销线程数量小于最大线程数量的线程将在闲置超过keepAliveTime
后被销毁。
long keepAliveTime
保证存活时间,若线程数超过了corePoolSize
,线程闲置时间超过了保证存活时间,该线程将被销毁。另外unit
指的是保活时间的单位。
BlockingQueue workQueue
阻塞队列,存放等待执行的任务,线程从workQueue中取任务,若无任务将阻塞等待。可以传入限制容量大小的队列或无限拓展队列。
ThreadFactory threadFactory
创建线程的工厂。
RejectedExecutionHandler handler
处理线程池及队列满载后的拒绝请求处理器。
线程池数量变化
假定一个核心线程数量为10、最大线程数量为20、线程队列限制最大为5的线程池,其内部线程、任务数量变化如下:
A-B
初始线程为空,每一次提交任务,容器比对当前维护线程数量都小于核心线程数量,故每次都新建线程直到达到了核心线程数量。
B-C
线程数量已经达到了核心线程数量,当前无空闲线程,任务堆积到队列中,直到任务队列达到最大数量。
C-D
由于任务队列已经达到饱和,所有线程仍然在被占用状态,但线程数量为达到最大线程数,尝试再次新建线程。
D-E
线程数量已经达到最大值,线程池已满,任务队列逐渐占满。
E-F
线程池数量达到最大、队列任务数达到最大,无法接受新的任务提交,对任务提交拒绝。
F-H
任务逐步被执行完成,队列内任务被清空,线程数量依然大于核心线程数量,当有线程空闲时间达到了保活时间将被销毁知道线程数量恢复核心线程数。
H-I
没有需要执行的任务,线程空闲,由于数量等于核心线程数,无需销毁线程,各个线程监听阻塞队列等待新的任务。