代码演示
private static final int COUNT_BITS = Integer.SIZE - 3;
private static final int CAPACITY = (1 << COUNT_BITS) - 1;
// runState 用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;
// workerCount 用27位低字节工作线程数量
private static int runStateOf(int c) { return c & ~CAPACITY; }
private static int workerCountOf(int c) { return c & CAPACITY; }
public static void main(String[] args) {
// 当前状态为:RUNNING,工作线程数量为:2
int ctl = RUNNING + 2;
System.out.println(runStateOf(ctl) == RUNNING);
System.out.println(workerCountOf(ctl));
}
运行测试类:
true
2
测试发现,变量int ctl
保存了两个数据信息,那么我们来分析它是如何做到的吧。
代码分析
将数据转换为二进制
// 29 (32-3)
private static final int COUNT_BITS = Integer.SIZE - 3;
// 00011111111111111111111111111111 (00100000000000000000000000000000 - 1)
private static final int CAPACITY = (1 << COUNT_BITS) - 1;
// 11100000000000000000000000000000
// ~CAPACITY;
// runState 用3位高字节保存多线程状态
// 11100000000000000000000000000000
private static final int RUNNING = -1 << COUNT_BITS;
// 00000000000000000000000000000000
private static final int SHUTDOWN = 0 << COUNT_BITS;
// 00100000000000000000000000000000
private static final int STOP = 1 << COUNT_BITS;
// 01000000000000000000000000000000
private static final int TIDYING = 2 << COUNT_BITS;
// 01100000000000000000000000000000
private static final int TERMINATED = 3 << COUNT_BITS;
分析计算当前状态与工作线程数量方法
private static int runStateOf(int c) { return c & ~CAPACITY; }
private static int workerCountOf(int c) { return c & CAPACITY; }
实际上是分别统计高位和地位的数字
从上图看出
- 线程状态有3位保存状态
- 工作线程数量有27位保存状态
结合逻辑运算,设计的非常巧妙