Java线程池------ThreadPoolExecutor剖析
1、核心变量ctl
首先看看源码:
//cas线程安全变量
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
//数量位数,29位,这里表示一个Interger的数(ctl)的后29位表示workCount数
private static final int COUNT_BITS = Integer.SIZE - 3;
//这个字段主要是为了后面计算,其实就是二进制的29个1.用于后面解析ctl变量的时候的与计算。
private static final int CAPACITY = (1 << COUNT_BITS) - 1;
// runStatus、运行状态存储在Integer的高3位中、下面是四种状态,代表线程池的四种运行状态。
private static final int RUNNING = -1 << COUNT_BITS;
private static final int SHUTDOWN = 0 << COUNT_BITS;
private static final int STOP = 1 << COUNT_BITS;
private static final int TIDYING = 2 << COUNT_BITS;
private static final int TERMINATED = 3 << COUNT_BITS;
// 解析runStatus、workerCount,打包ctl方法
private static int runStateOf(int c) {
return c & ~CAPACITY; }
private static int workerCountOf(int c) {
return c & CAPACITY;