首页  

ThreadPoolExecutor中的ctl变量     所属分类 java 浏览量 1480
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
    private static final int COUNT_BITS = Integer.SIZE - 3;
    private static final int CAPACITY   = (1 << COUNT_BITS) - 1;

    // 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;

    // Packing and unpacking ctl
    private static int runStateOf(int c)     { return c & ~CAPACITY; }
    private static int workerCountOf(int c)  { return c & CAPACITY; }
    private static int ctlOf(int rs, int wc) { return rs | wc; }


ctl包含两个值 

workerCount 线程数
runState 线程池的状态, Running,Shutdown,Stop,Tidying,Terminate 

29位表示workerCount,3位表示当前线程池的状态。
高3位状态值,低28位 线程数
runState is stored in the high-order bits



COUNT_BITS Integer.SIZE-3  明线程数 用29位表示
CAPACITY 左移29位 减一  ,  

ctl&CAPACITY  获取当前线程数


ThreadpoolCtlTest.java import java.util.concurrent.atomic.AtomicInteger; public class ThreadpoolCtlTest { private static final int COUNT_BITS = Integer.SIZE - 3; private static final int CAPACITY = (1 << COUNT_BITS) - 1; // 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; // Packing and unpacking ctl private static int runStateOf(int c) { return c & ~CAPACITY; } private static int workerCountOf(int c) { return c & CAPACITY; } private static int ctlOf(int rs, int wc) { return rs | wc; } private final static AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0)); private static boolean isRunning(int c) { return c < SHUTDOWN; } private static void printCtl(){ int c = ctl.get(); System.out.print(c+","); System.out.print(isRunning(c)+","); System.out.print(runStateOf(c)+","); System.out.println(workerCountOf(c)); } public static void main(String[] args) throws Exception { System.out.println(0+","+ (~0)); System.out.println(1+","+ (~1)); System.out.println(CAPACITY); System.out.println(~CAPACITY); printCtl(); ctl.set(ctlOf(RUNNING, 3)); printCtl(); ctl.set(ctlOf(SHUTDOWN, 3)); printCtl(); } }
输出 0,-1 1,-2 536870911 -536870912 -536870912,true,-536870912,0 -536870909,true,-536870912,3 3,false,0,3

上一篇     下一篇
指数基金的几种形式

线程池要点

员工离职前的9种征兆

2019年一季度A股投资者结构

java线程池实例

tomcat线程池要点