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