源码阅读 - 线程池:线程池原理(四)addWorker--execute方法的前奏

private boolean addWorker(Runnable firstTask, boolean core);

方法参数:

firstTask – 需要执行的任务,和worker进行绑定,可以为null

core ------- 是否为核心线程,如果为true,则使用corePoolSize;否则使用maxPoolSize

private boolean addWorker(Runnable firstTask, boolean core) {
    retry:
    for (;;) {
        int c = ctl.get();
        int rs = runStateOf(c);

        /*
        if rs >= SHUTDOWN :
            if rs != SHUTDOWN //在STOP/TIDYING/TERMINATED状态下不能添加worker
            
            if rs == SHUTDOWN && firstTask != null // 在SHUTDOWN状态下只能添加null任务
            
            if rs == SHUTDOWN && firstTask == null && workQueue.isEmpty // 任务队列为空,没有必要添加新的工作线程,firstTask = null是为了额外添加一个线程,消耗任务队列
        */
        if (rs >= SHUTDOWN &&
            ! (rs == SHUTDOWN &&
               firstTask == null &&
               ! workQueue.isEmpty()))
            return false;
        for (;;) {
            int wc = workerCountOf(c);
            // 工作线程饱和
            if (wc >= CAPACITY ||
                wc >= (core ? corePoolSize : maximumPoolSize))
                return false;
            
            if (compareAndIncrementWorkerCount(c))
                break retry;
            //cas自增失败
            c = ctl.get();  // Re-read ctl
            //状态发生改变
            if (runStateOf(c) != rs)
                continue retry;
            // else CAS failed due to workerCount change; retry inner loop
        }
    }


    //添加任务
    boolean workerStarted = false;
    boolean workerAdded = false;
    Worker w = null;
    try {
        w = new Worker(firstTask);
        final Thread t = w.thread;
        if (t != null) {
            final ReentrantLock mainLock = this.mainLock;
            mainLock.lock();
            try {
                // Recheck while holding lock.
                // Back out on ThreadFactory failure or if
                // shut down before lock acquired.
                int rs = runStateOf(ctl.get());
                /*
                if rs == RUNNING    //线程池状态为RUNNING
                
                if rs == SHUTDOWN && firstTask == null    //线程池状态为SHUTDOWN,而且firstTask == null
                */
                if (rs < SHUTDOWN ||
                    (rs == SHUTDOWN && firstTask == null)) {
                    // isAlive 返回true,说明线程非按照正常过程被启动,可以导致wokerStarted = false
                    if (t.isAlive()) // precheck that t is startable
                        throw new IllegalThreadStateException();
                    workers.add(w);
                    int s = workers.size();
                    if (s > largestPoolSize)
                        largestPoolSize = s;
                    workerAdded = true;
                }
            } finally {
                mainLock.unlock();
            }
            if (workerAdded) {
                t.start();
                workerStarted = true;
            }
        }
    } finally {
        if (! workerStarted)
            addWorkerFailed(w);
    }
    return workerStarted;
}

addWorker(Runnable firstTask,bool core)只有在两种情况下会返回true

1、当线程池状态为SHUTDOWN时,且工作任务队列不为空,这时候只有addWorker(null)返回为true。

2、当线程池状态为RUNNING时,判断工作线程数量是否饱和(即判断workerCount),如果不饱和,添加并返回true。代码如下:

wc >= CAPACITY || wc >= (core ? corePoolSize : maximumPoolSize)

这里有必要解释一下addWorker(null)的用意,这种调用只会出现在SHUTDOWN状态并且工作任务队列不为空的情况,为的是新建一个工作线程从工作任务队列获取取任务执行,以尽快的结束工作任务队列的任务。

你可能感兴趣的:(源码阅读,线程池)