注:本文的分析和源码基于jdk1.7;
一、ThreadPoolExecutor创建
ThreadPoolExecutor作为java.util.concurrent包中核心的类,先看下类型的结构:
最顶级的接口都是Executor,而ThreadPoolExecutor继承于抽象类AbstractExecutorService,提供以下4个构造函数用于创建:
public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,ong keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue);
public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory)
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue,RejectedExecutionHandler handler)
public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler)
前面的3个方法都是使用通过this调用最后一个方法,没有指定的构造参数使用默认参数,参数解析:
1、
/**
* Core pool size is the minimum number of workers to keep alive
* (and not allow to time out etc) unless allowCoreThreadTimeOut
* is set, in which case the minimum is zero.
*/
private volatile int corePoolSize;
线程池核心线程数大小,初始化时核心线程数也是0,除非先调用prestartCoreThread或者prestartAllCoreThreads先创建核心线程;在没有设置allowCoreThreadTimeOut为true情况下,核心线程不会销毁;
2、
/**
* Maximum pool size. Note that the actual maximum is internally
* bounded by CAPACITY.
*/
private volatile int maximumPoolSize;
线程池线程数最大值,达到最大值后线程池不会再增加线程执行任务,任务会进入等待队列或者由拒绝策略处理;
该值实际的可设置最大值不是Integer.MAX_VALUE,而是常量CAPACITY(后面再解析常量)
3、
/**
* Timeout in nanoseconds for idle threads waiting for work.
* Threads use this timeout when there are more than corePoolSize
* present or if allowCoreThreadTimeOut. Otherwise they wait
* forever for new work.
*/
private volatile long keepAliveTime;
空闲工作线程的空闲时间;超过corePoolSize的线程或者allowCoreThreadTimeOut为true的主线程使用这个作为超时时间;
否则线程一直等待任务或关闭;
4、
/**
* The queue used for holding tasks and handing off to worker
* threads. We do not require that workQueue.poll() returning
* null necessarily means that workQueue.isEmpty(), so rely
* solely on isEmpty to see if the queue is empty (which we must
* do for example when deciding whether to transition from
* SHUTDOWN to TIDYING). This accommodates special-purpose
* queues such as DelayQueues for which poll() is allowed to
* return null even if it may later return non-null when delays
* expire.
*/
private final BlockingQueue<Runnable> workQueue;
这个队列用于保存任