线程池的原理(二)-------addWorker方法

直接上源码分析每一步:

/**
 * Checks if a new worker can be added with respect to current
 * pool state and the given bound (either core or maximum). If so,
 * the worker count is adjusted accordingly, and, if possible, a
 * new worker is created and started, running firstTask as its
 * first task. This method returns false if the pool is stopped or
 * eligible to shut down. It also returns false if the thread
 * factory fails to create a thread when asked.  If the thread
 * creation fails, either due to the thread factory returning
 * null, or due to an exception (typically OutOfMemoryError in
 * Thread.start()), we roll back cleanly.
 *
 * @param firstTask the task the new thread should run first (or
 * null if none). Workers are created with an initial first task
 * (in method execute()) to bypass queuing when there are fewer
 * than corePoolSize threads (in which case we always start one),
 * or when the queue is full (in which case we must bypass queue).
 * Initially idle threads are usually created via
 * prestartCoreThread or to replace other dying workers.
 *
 * @param core if true use corePoolSize as bound, else
 * maximumPoolSize. (A boolean indicator is used here rather than a
 * value to ensure reads of fresh values after checking other pool
 * state).
 * @return true if successful
 */
private boolean addWorker(Runnable firstTask, boolean core) {


      //第一步:

    // CAS更新线程池数量
    //循环CAS操作,将线程池中的线程数+1
    retry:
    for (;;) {
        int c = ctl.get();
        int rs = runStateOf(c);

        // Check if queue empty only if necessary.
        //(1)如果线程是运行状态时运行
        //(2)线程状态为关闭&&firstTask == null&&队列不为空
        if (rs >= SHUTDOWN &&
            ! (rs == SHUTDOWN &&
               firstTask == null &&
               ! workQueue.isEmpty()))
            return false;

        for (;;) {
            //获取正在执行的线程
            int wc = workerCountOf(c);
             //(1)工作线程数大于线程容量
             //(2)core :工作线程数大于核心线程数量 或者 工作线程数量大于最大线程数 
            if (wc >= CAPACITY ||
                wc >= (core ? corePoolSize : maximumPoolSize))
                return false;
            //cas线程数加1,在线程池中将要添加的线程预留出来,成功则退出,失败则循环,unsafe方法实现
            if (compareAndIncrementWorkerCount(c))
            //成功则跳出循环
                break retry;
            //状态发生变化则继续执行
            c = ctl.get();  // Re-read ctl
            if (runStateOf(c) != rs)
                continue retry;
            // else CAS failed due to workerCount change; retry inner loop
        }
    }
    




    //第二步:新建线程成功后,加入到线程池workers中
    boolean workerStarted = false;
    boolean workerAdded = false;
    Worker w = null;
    try {
        //将线程添加到Worker中
        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());
                //(1)线程池的状态为执行中
                //(2)shutdown时,添加空线程
                if (rs < SHUTDOWN ||
                    (rs == SHUTDOWN && firstTask == null)) {
                    //判断添加的任务状态,如果任务已经开始执行则抛异常
                    if (t.isAlive()) // precheck that t is startable
                        //如果任务已经开始执行,则抛出异常
                        throw new IllegalThreadStateException();
                    //将新建的worker加入到worker集合heshset
                    workers.add(w);
                    int s = workers.size();
                    if (s > largestPoolSize)
                         //更新最大值
                        largestPoolSize = s;
                    workerAdded = true;
                }
            } finally {
                //释放锁
                mainLock.unlock();
            }
            if (workerAdded) {
                //启动线程
                t.start();
                workerStarted = true;
            }
        }
    } finally {
          //如果失败,调用addWorkerFailed()函数
        if (!workerStarted)
            
            addWorkerFailed(w);
    }
    return workerStarted;
}

addWorkerFailed:添加失败函数

  private void addWorkerFailed(Worker w) {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            if (w != null)
                //删除worker
                workers.remove(w);
                //恢复worker数
            decrementWorkerCount();
            tryTerminate();
        } finally {
            mainLock.unlock();
        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_40403930/article/details/89067042