ThreadPoolExecutor
构造方法:
/**
* Creates a new {@codeThreadPoolExecutor} with the given initial
* parameters and default thread factory and rejected execution handler.
* It may be more convenient to use one of the {@linkExecutors} factory
* methods instead of this general purpose constructor.
*
*@paramcorePoolSizethe number of threads to keep in the pool, even
* if they are idle, unless {@codeallowCoreThreadTimeOut} is set
*@parammaximumPoolSizethe maximum number of threads to allow in the
* pool
*@paramkeepAliveTimewhen 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.
*@paramunitthe time unit for the {@codekeepAliveTime} argument
*@paramworkQueuethe queue to use for holding tasks before they are
* executed. This queue will hold only the {@codeRunnable}
* tasks submitted by the {@codeexecute} method.
*@throwsIllegalArgumentException if one of the following holds:
* {@codecorePoolSize < 0}
* {@codekeepAliveTime < 0}
* {@codemaximumPoolSize <= 0}
* {@codemaximumPoolSize < corePoolSize}
*@throwsNullPointerException if {@codeworkQueue} is null
*/
publicThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue) {
this(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue,
Executors.defaultThreadFactory(),defaultHandler);
}
构造方法参数
corePoolSize:核心线程池大小
maximumPoolSize:最大线程池大小
keepAliveTime:线程池中超过corePoolSize数目的空闲线程最大存活时间;可以allowCoreThreadTimeOut(true)使得核心线程超过有效时间被kill掉
TimeUnitkeepAliveTime:时间单位
workQueue:阻塞任务队列
threadFactory:新建线程工厂
RejectedExecutionHandler:当提交任务数超过maxmumPoolSize+workQueue之和时,任务会交给RejectedExecutionHandler来处理
其中比较容易让人误解的是:corePoolSize,maximumPoolSize,workQueue之间关系。
1.当线程池小于corePoolSize时,新提交任务将创建一个新线程执行任务,即使此时线程池中存在空闲线程。
2.当线程池达到corePoolSize时,新提交任务将被放入workQueue中,等待线程池中任务调度执行
3.当workQueue已满,且maximumPoolSize>corePoolSize时,新提交任务会创建新线程执行任务
4.当提交任务数超过maximumPoolSize时,新提交任务由RejectedExecutionHandler处理
5.当线程池中超过corePoolSize线程,空闲时间达到keepAliveTime时,关闭空闲线程
6.当设置allowCoreThreadTimeOut(true)时,线程池中corePoolSize线程空闲时间达到keepAliveTime也将关闭
workQueue:
SynchronousQueue:无容量的阻塞队列
ArrayBlockingQueue:以数组实现的阻塞队列,固定大小
LinkedBlockingQueue:以链表实现的阻塞队列,无固定大小
PriorityBlockingQueue:优先级队列阻塞队列,需要传入Comparator来比较优先级
DelayQueue:内部是一个PriorityQueue,优先级高低以Delayed来决定
类继承关系:public classDelayQueue <E extends Delayed>extends AbstractQueue implements BlockingQueue
其中Delayed
public interface Delayed extends Comparable {
long getDelay(TimeUnit unit);
}
ForwodingBlockingQueue: