java线程池的源码分析

2022-03-11  本文已影响0人  jxcyly1985

线程池中的任务执行顺序

 public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        /*
         * Proceed in 3 steps:
         *
         * 1. If fewer than corePoolSize threads are running, try to
         * start a new thread with the given command as its first
         * task.  The call to addWorker atomically checks runState and
         * workerCount, and so prevents false alarms that would add
         * threads when it shouldn't, by returning false.
         *
         * 2. If a task can be successfully queued, then we still need
         * to double-check whether we should have added a thread
         * (because existing ones died since last checking) or that
         * the pool shut down since entry into this method. So we
         * recheck state and if necessary roll back the enqueuing if
         * stopped, or start a new thread if there are none.
         *
         * 3. If we cannot queue task, then we try to add a new
         * thread.  If it fails, we know we are shut down or saturated
         * and so reject the task.
         */
        int c = ctl.get();
        if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        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))
            reject(command);
    }

1、首先先判断核心线程
2、如果插入任务队列成功,重新检测当前线程池是否关闭,否则移除(recheck检查)
3、创建单独的线程(这个机制是提供更灵活的线程创建方式,提供更快的任务响应性)

workerCountOf的recheck操作是为了防止如果出现线程执行退出或者死亡退出
考虑 corePoolSize == 0 ,queue== LinkedBlockingQueue ,keepTimeout ==0 的场景,如果创建的非核心线程执行完毕,当前则没有可执行任务的线程,当任务执行完之后

wc > corePoolSize , getTask执行timed流程,因此当前会没有执行任务的线程。

addWorker

addWorker内部通过非阻塞方式锁实现corePoolSize的线程安全

SynchronousQueue

CacheThreadPoolExecutor使用这个队列,这个队列,如果没有getTask在take则会返回false,从而创建一个非核心线程处理command任务

线程的线程退出

private void processWorkerExit(Worker w, boolean completedAbruptly) {
        if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted
            decrementWorkerCount();

        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            completedTaskCount += w.completedTasks;
            workers.remove(w);
        } finally {
            mainLock.unlock();
        }

        tryTerminate();

        int c = ctl.get();
        if (runStateLessThan(c, STOP)) {
            if (!completedAbruptly) {
                int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
                if (min == 0 && ! workQueue.isEmpty())
                    min = 1;
                if (workerCountOf(c) >= min)
                    return; // replacement not needed
            }
            addWorker(null, false);
        }
    }

1、异常退出,需要重新补充一个线程
2、任务队列不为空,则最小需要保持存在一个线程
3、如果小于核心线程corePoolSize,需要补充一个线程

在临界场景,(考虑corePoolSize是0的场景)会出现execute(command)时候和processWorkerExit时候,同时在addWoker

execute时候判断当前没有worker,同时processWorkerExit的时候也没有worker,这个时候会创建2个非core线程

上一篇下一篇

猜你喜欢

热点阅读