ThreadPoolExecutor学习笔记

线程池状态:

高3位表示"线程池状态"
低29位表示"线程池中的任务数量"

public class ThreadPoolExecutor extends AbstractExecutorService {
    
    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; }
public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        int c = ctl.get();
        if (workerCountOf(c) < corePoolSize) {   // 如果工作线程数 < corePoolSize,就new 一个新的线程
            if (addWorker(command, true))
                return;
            c = ctl.get();                  // 如果线程new 失败了,说明不满足runState 和workerCount 的要求,有并发的操作,重新获取一次标志位
        }
        if (isRunning(c) && workQueue.offer(command)) {       // 如果是运行状态,就往队列里添加任务
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))          // 如果不是运行状态了,就从队列里移除任务,并执行拒绝策略
                reject(command);
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        else if (!addWorker(command, false))             //如果队列也添加不了,就new thread直到maxPoolSize,如果失败就执行拒绝策略
            reject(command);
    }

Worker

private final class Worker
        extends AbstractQueuedSynchronizer
        implements Runnable
    {
     
        /** Thread this worker is running in.  Null if factory fails. */
        final Thread thread;
        /** Initial task to run.  Possibly null. */
        Runnable firstTask;
        /** Per-thread task counter */
        volatile long completedTasks;

        /**
         * Creates with given first task and thread from ThreadFactory.
         * @param firstTask the first task (null if none)
         */
        Worker(Runnable firstTask) {
            setState(-1); // inhibit interrupts until runWorker
            this.firstTask = firstTask;
            this.thread = getThreadFactory().newThread(this);
        }

        /** Delegates main run loop to outer runWorker  */
        public void run() {
            runWorker(this);
        }

你可能感兴趣的:(ThreadPoolExecutor学习笔记)