在ThreadPoolExecutor中的几个重要变量
基础变量 COUNT_BITS、CAPACITY
COUNT_BITS = 29
这是最基础的值,线程池内部维护的五个状态值和CAPACITY都是通过COUNT_BITS移位来计算的
private static final int COUNT_BITS = Integer.SIZE - 3;//29
private static final int CAPACITY = (1 << COUNT_BITS) - 1;//(1<<29)-1=536870911
private static final int RUNNING = -1 << COUNT_BITS;//(-1<<29)=-536870912
private static final int SHUTDOWN = 0 << COUNT_BITS;//(0<<29)=0
private static final int STOP = 1 << COUNT_BITS;// (1<<29)=536870912
private static final int TIDYING = 2 << COUNT_BITS;//(2<<29)=1073741824
private static final int TERMINATED = 3 << COUNT_BITS;//(3<<29)=1610612736
变量名 32位二进制补码 真值
CAPACITY 00011111111111111111111111111111 536870911
~CAPACITY 11100000000000000000000000000000 -536870912
RUNNING 11100000000000000000000000000000 -536870912
SHUTDOWN 00000000000000000000000000000000 0
STOP 00100000000000000000000000000000 536870912
TIDYING 01000000000000000000000000000000 1073741824
TERMINATED 01100000000000000000000000000000 1610612736
CAPACITY = (1 << COUNT_BITS) - 1 (十进制)
= (1 << 29) - 1 (十进制)
= 536,870,911 (十进制)
= 0001 1111 1111 1111 1111 1111 1111 1111 (二进制补码)
线程池使用一个复合变量ctl来同时表示线程池的运行状态和工作的线程数
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
所以 & CAPACITY 可以保留后29位的二进制数
& ~CAPACITY可以保留前3位的二进制数
分别用于计算前3位:线程池的运行状态以及后29位:线程池中工作的线程数
private static int runStateOf(int c) { return c & ~CAPACITY; }
private static int workerCountOf(int c) { return c & CAPACITY; }
ctl的初始化方法
private static int ctlOf(int rs, int wc) { return rs | wc; }
判断线程池是否在运行的方法isRunning()
private static boolean isRunning(int c) {
return c < SHUTDOWN;
}
因为SHUTDOWN状态为0,只有RUNNING状态比它小