/**
* 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:
* {@code corePoolSize < 0}
* {@code keepAliveTime < 0}
* {@code maximumPoolSize <= 0}
* {@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) {
}
保留在池中的线程数,哪怕它们是空闲的,除非设置了allowCoreThreadTimeOut
池中的最大线程数。
当线程的数量大于corePoolSize,这是多余空闲线程的最大存活时间,当空间时间达到keepAliveTime值时,多余的线程会被销毁并等待新任务。
为keepAliveTime参数设置的时间单位
在任务执行之前用于保存任务的队列。这个队列将只保存由execute方法提交的Runnable任务。当池中的工作线程数大于corePoolSize时,这时新进来的任务会被放到该队列中。
使用自定义的线程工厂来创建线程,一般用jdk自带的Executors.defaultThreadFactory()即可,或者guava库的ThreadFactoryBuilder。
当没有空闲线程并且线程数已经等于maxnumPoolSize时,如何拒绝新的任务请求。
jdk实现的RejectedExecutionHandler有:
AbortPolicy,总是抛出RejectedExecutionException,默认就是AbortPolicy。
CallerRunsPolicy,如果线程池没有关闭,在调用者的线程中执行任务。如果线程池已经关闭,那么直接被丢弃任务。
DiscardOldestPolicy,如果线程池没有关闭,那么丢弃队列中最老的任务,并执行新任务。如果线程池已经关闭,那么直接被丢弃任务。
DiscardPolicy,什么都不做,直接丢弃任务。
线程池中线程数小于corePoolSize时,新任务将创建一个新线程执行任务,不论此时线程池中是否存在空闲线程。
线程池中线程数达到corePoolSize时,新任务将被放入workQueue中,等待线程池中任务调度执行;
当workQueue已满,且maximumPoolSize>corePoolSize时,新任务会创建新线程执行任务;
当workQueue已满,且提交任务数超过maximumPoolSize,任务由RejectedExecutionHandler处理;
当线程池中线程数超过corePoolSize,且超过这部分的空闲时间达到keepAliveTime时,回收该线程;
如果设置allowCoreThreadTimeOut(true)时,线程池中corePoolSize范围内的线程空闲时间达到keepAliveTime也将回收;