1.变量
ThreadPoolExecutor先定义了这几个常量,初看时一脸懵逼,其实它就是用int的二进制高三位来表示线程池的状态,
先回顾一下位运算:
- <<’左移:右边空出的位置补0,其值相当于乘以2。
- ‘>>’右移:左边空出的位,如果是正数则补0,若为负数则补0或1,取决于所用的计算机系统OS X中补1。其值相当于除以2。
- 负数二进制由它的绝对值取反后加1
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0)); private static final int COUNT_BITS = Integer.SIZE - 3;// 29 private static final int CAPACITY = (1 << COUNT_BITS) - 1; // 1<<29=00100000 00000000 00000000 00000000 再减1=00011111 11111111 11111111 11111111 // 1的二进制是001,取反是110,再加1是111,111就是-1的二进制,再左移29, private static final int RUNNING = -1 << COUNT_BITS;// 11100000 00000000 00000000 00000000 private static final int SHUTDOWN = 0 << COUNT_BITS;// 00000000 00000000 00000000 00000000 private static final int STOP = 1 << COUNT_BITS;// 00100000 00000000 00000000 00000000 private static final int TIDYING = 2 << COUNT_BITS;// 01000000 00000000 00000000 00000000 private static final int TERMINATED = 3 << COUNT_BITS;// 01100000 00000000 00000000 00000000