线程池的状态参数分析
线程池的状态参数分析
线程池的原子变量
ctl的创建如下:
1 | private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0)); |
上面中的RUNNING为:
1 | private static final int RUNNING = -1 << COUNT_BITS; |
-1做左移COUNT_BITS运算
COUNT_BITS如下:
1 | private static final int COUNT_BITS = Integer.SIZE - 3; |
其中Integer.SIZE=32,得知COUNT_BITS为29,那么RUNNING为左移-1左移29位,-1的二进制表示为11111111111111111111111111111111,左移29位11100000000000000000000000000000。
ctlOf的计算方式如下:
1 | private static int ctlOf(int rs, int wc) { return rs | wc; } |
线程的运行状态与线程数量做或运算,所以运行状态左移29位后,将高3位表示运行状态,低29位表示线程数量。
由于线程池的运行状态只有如下几种:
1 | // runState is stored in the high-order bits |
所以高3位足以表示所有的运行状态。
线程池提供了运行状态和线程数量的计算方法:
1 | // Packing and unpacking ctl |
运算常量
1 | private static final int CAPACITY = (1 << COUNT_BITS) - 1; |
所以runStateOf 为舍弃掉低29位后的值,workerCountOf 为舍弃掉高3位后的值。