线程池的状态参数分析

线程池的状态参数分析

线程池的原子变量

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
2
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
2
3
4
5
6
// runState is stored in the high-order bits
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;

所以高3位足以表示所有的运行状态。
线程池提供了运行状态和线程数量的计算方法:

1
2
3
// Packing and unpacking ctl
private static int runStateOf(int c) { return c & ~CAPACITY; }
private static int workerCountOf(int c) { return c & CAPACITY; }

运算常量

1
2
3
4
5
6
private static final int CAPACITY   = (1 << COUNT_BITS) - 1;

CAPACITY = (1 << 29) -1
= (00000000000000000000000000000001 << 29) - 1
= 00100000000000000000000000000000 - 1
= 00011111111111111111111111111111

所以runStateOf 为舍弃掉低29位后的值,workerCountOf 为舍弃掉高3位后的值。