// runState is stored in the high-order bits
/**
* The number of bits used to represent an {@code int} value in two's
* complement binary form.
*
* @since 1.5
*/
@Native public static final int SIZE = 32;
private static final int COUNT_BITS = Integer.SIZE - 3;
//-1 左移 32位 ,负数的左移,右边一直补0,所以右边是29个0,-1二进制源码是101,
//但是计算机使用的是补码,补码为 原码除符号位的各个位取反(110),然后反码+1(111),
//所以RUNNING=11100000000000000000000000000000
private static final int RUNNING = -1 << COUNT_BITS;
//同样 SHUTDOWN=000 00000000000000000000000000000
private static final int SHUTDOWN = 0 << COUNT_BITS;
// 001 00000000000000000000000000000
private static final int STOP = 1 << COUNT_BITS;
// 010 00000000000000000000000000000
private static final int TIDYING = 2 << COUNT_BITS;
// 011 00000000000000000000000000000
private static final int TERMINATED = 3 << COUNT_BITS;
以上为Java线程池表示线程池状态的方式,为32位的高三位,线程池线程数为32位的低29位。
// Packing and unpacking ctl
//获取高三位的值
private static int runStateOf(int c) { return c & ~CAPACITY; }
//获取低29位的值
private static int workerCountOf(int c) { return c & CAPACITY; }
//将高三位和低29位合并 即可得到ctl的值
private static int ctlOf(int rs, int wc) { return rs | wc; }
举个栗子:
假设线程池状态为RUNNING,有4个线程(WorkerCount)。
ctl = 111 00000000000000000000000000000100
此时runStateOf(int c)执行 c & ~ CAPACITY, CAPACITY 值为 (1 << COUNT_BITS) - 1 ,即 00011111111111111111111111111111,ctl 111 00000000000000000000000000000100 和 CAPACITY相与
CAPACITY 取反:
~ 00011111111111111111111111111111 = 111 000000000000000000000000000000.
~CAPACITY 111 000000000000000000000000000000
&
ctl 111 000000000000000000000000000100
= 111 000000000000000000000000000000
所得结果只有高三位有可能不全为0,低29一定全为0,这样高三位就可能用来表示线程池的各个状态。
workerCountOf(int c)同理。
ctlOf(int rs, int wc)为将线程池状态和线程池的线程数量的状态合并为ctl.使用上面的例子。
RUNNING: 111 000000000000000000000000000000
|
WorkCount:000 000000000000000000000000000100
=111 000000000000000000000000000100