一、基本构造函数
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.acc = System.getSecurityManager() == null ?
null :
AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
corePoolSize:核心线程数量;
maximumPoolSize:最大线程数量。当工作任务队列饱和时,将会增加工作线程数量,该值为增长的最大值;
满足条件:maximumPoolSize >= corePoolSize;
keepAliveTime:空闲线程的超时时间。默认是指超过corePoolSize的部分线程,但如果设置allowsCoreThreadTimeOut(true),只要工作线程数量大于1,都会对空闲线程进行超时检测。
unit:keepAliveTime的单位,最后都会转换成纳秒。
workQueue:工作线程数量超过核心线程数量时,会将任务加入工作任务队列。
threadFactory:创建线程的工厂方法,每次创建线程时调用threadFactory的newThread方法
handler:拒绝策略,当线程池饱和或者线程池的状态不支持提交新的任务将会调用其reject方法,默认实现为抛出异常。
下面是一些参数数量较少的构造函数,当本质都是调用了上面的构造函数:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), handler);
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory, defaultHandler);
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
二、一些重要的变量
//工作任务队列
private final BlockingQueue workQueue;
//操纵工作线程集合(workers)的锁
private final ReentrantLock mainLock = new ReentrantLock();
//工作线程集合,操作时,需要获取mainLock
private final HashSet workers = new HashSet();
//是否允许核心线程超时退出
private volatile boolean allowCoreThreadTimeOut;//高3位是线程池的运行状态,低29位为线程数量
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
private static final int COUNT_BITS = Integer.SIZE - 3;
//工作线程数量的最大值,2^29-1
private static final int CAPACITY = (1 << COUNT_BITS) - 1;//线程池的五种状态
private static final int RUNNING = -1 << COUNT_BITS;
private static final int SHUTDOWN = 0 << COUNT_BITS;//调用shutdown,等待队列任务执行完成
private static final int STOP = 1 << COUNT_BITS;//调用shutdownNow ,直接返回,不等待队列中任务执行完成
private static final int TIDYING = 2 << COUNT_BITS;//工作线程集合为空
private static final int TERMINATED = 3 << COUNT_BITS;//terminated回调完成//1610612736
其中ctl可以联系ConcurrentHashMap中的ctl,doug lea都是用这个同名参数来存储状态。