原理剖析(第 003 篇)ThreadPoolExecutor工作原理分析

原理剖析(第 003 篇)ThreadPoolExecutor工作原理分析

一靠欢、大致介紹

1放妈、相信大家都用過線程池,對該類ThreadPoolExecutor應(yīng)該一點都不陌生了湿右;
2诅妹、我們之所以要用到線程池,線程池主要用來解決線程生命周期開銷問題和資源不足問題;
3吭狡、我們通過對多個任務(wù)重用線程以及控制線程池的數(shù)目可以有效防止資源不足的情況尖殃;
4、本章節(jié)就著重和大家分享分析一下JDK8的ThreadPoolExecutor核心類划煮,看看線程池是如何工作的送丰;

二、基本字段方法介紹

2.1 構(gòu)造器

1般此、四個構(gòu)造器:
    // 構(gòu)造器一
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }
    
    // 構(gòu)造器二
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             threadFactory, defaultHandler);
    }

    // 構(gòu)造器三
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              RejectedExecutionHandler handler) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), handler);
    }

    // 構(gòu)造器四
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

2蚪战、通過仔細查看構(gòu)造器代碼,發(fā)現(xiàn)最終都是調(diào)用構(gòu)造器四铐懊,緊接著賦值了一堆的字段,接下來我們先看看這些字段是什么含義瞎疼;

2.2 成員變量字段

1科乎、corePoolSize:核心運行的線程池數(shù)量大小,當(dāng)線程數(shù)量超過該值時贼急,就需要將超過該數(shù)量值的線程放到等待隊列中茅茂;

2、maximumPoolSize:線程池最大能容納的線程數(shù)(該數(shù)量已經(jīng)包含了corePoolSize數(shù)量)太抓,當(dāng)線程數(shù)量超過該值時空闲,則會拒絕執(zhí)行處理策略;

3走敌、workQueue:等待隊列碴倾,當(dāng)達到corePoolSize的時候,就將新加入的線程追加到workQueue該等待隊列中掉丽;
              當(dāng)然BlockingQueue類也是一個抽象類跌榔,也有很多子類來實現(xiàn)不同的隊列等待;
              
              一般來說捶障,阻塞隊列有一下幾種僧须,ArrayBlockingQueue;LinkedBlockingQueue/SynchronousQueue/ArrayBlockingQueue/
              PriorityBlockingQueue使用較少,一般使用LinkedBlockingQueue和Synchronous项炼。

4担平、keepAliveTime:表示線程沒有任務(wù)執(zhí)行時最多保持多久存活時間,默認情況下當(dāng)線程數(shù)量大于corePoolSize后keepAliveTime才會起作用
                  并生效锭部,一旦線程池的數(shù)量小于corePoolSize后keepAliveTime又不起作用了暂论;
                  
                  但是如果調(diào)用了allowCoreThreadTimeOut(boolean)方法,在線程池中的線程數(shù)不大于corePoolSize時空免,
                  keepAliveTime參數(shù)也會起作用苏揣,直到線程池中的線程數(shù)為0杉武;

5寂嘉、threadFactory:新創(chuàng)建線程出生的地方押搪;

6、handler:拒絕執(zhí)行處理抽象類杈湾,就是說當(dāng)線程池在一些場景中,不能處理新加入的線程任務(wù)時,會通過該對象處理拒絕策略析恢;
            該對象RejectedExecutionHandler有四個實現(xiàn)類,即四種策略秧饮,讓我們有選擇性的在什么場景下該怎么使用拒絕策略映挂;
            策略一( CallerRunsPolicy ):只要線程池沒關(guān)閉,就直接用調(diào)用者所在線程來運行任務(wù)盗尸;
            策略二( AbortPolicy ):默認策略柑船,直接拋出RejectedExecutionException異常;
            策略三( DiscardPolicy ):執(zhí)行空操作泼各,什么也不干鞍时,拒絕任務(wù)后也不做任何回應(yīng);
            策略四( DiscardOldestPolicy ):將隊列中存活最久的那個未執(zhí)行的任務(wù)拋棄掉扣蜻,然后將當(dāng)前新的線程放進去逆巍;
   
7、largestPoolSize:變量記錄了線程池在整個生命周期中曾經(jīng)出現(xiàn)的最大線程個數(shù)莽使;

8锐极、allowCoreThreadTimeOut:當(dāng)為true時,和弦線程也有超時退出的概念一說芳肌;

2.3 成員方法

1灵再、AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
   // 原子變量值,是一個復(fù)核類型的成員變量庇勃,是一個原子整數(shù)檬嘀,借助高低位包裝了兩個概念:
   
2、int COUNT_BITS = Integer.SIZE - 3;
   // 偏移位數(shù)责嚷,常量值29鸳兽,之所以偏移29,目的是將32位的原子變量值ctl的高3位設(shè)置為線程池的狀態(tài)罕拂,低29位作為線程池大小數(shù)量值揍异;
    
3、int CAPACITY   = (1 << COUNT_BITS) - 1;
   // 線程池的最大容量值爆班;
    
4衷掷、線程池的狀態(tài),原子變量值ctl的高三位:
   int RUNNING    = -1 << COUNT_BITS; // 接受新任務(wù)柿菩,并處理隊列任務(wù)
   int SHUTDOWN   =  0 << COUNT_BITS; // 不接受新任務(wù)戚嗅,但會處理隊列任務(wù)
   int STOP       =  1 << COUNT_BITS; // 不接受新任務(wù),不會處理隊列任務(wù),而且會中斷正在處理過程中的任務(wù)
   int TIDYING    =  2 << COUNT_BITS; // 所有的任務(wù)已結(jié)束懦胞,workerCount為0替久,線程過渡到TIDYING狀態(tài),將會執(zhí)行terminated()鉤子方法
   int TERMINATED =  3 << COUNT_BITS; // terminated()方法已經(jīng)完成
   
5躏尉、HashSet<Worker> workers = new HashSet<Worker>(); 
   // 存放工作線程的線程池蚯根;

2.4 成員方法

1、public void execute(Runnable command)
   // 提交任務(wù)胀糜,添加Runnable對象到線程池颅拦,由線程池調(diào)度執(zhí)行

2、private static int workerCountOf(int c)  { return c & CAPACITY; }
   // c & 高3位為0教藻,低29位為1的CAPACITY距帅,用于獲取低29位的線程數(shù)量

3、private boolean addWorker(Runnable firstTask, boolean core)
   // 添加worker工作線程括堤,根據(jù)邊界值來決定是否創(chuàng)建新的線程

4锥债、private static boolean isRunning(int c)
   // c通常一般為ctl,ctl值小于0痊臭,則處于可以接受新任務(wù)狀態(tài)

5、final void reject(Runnable command) 
   // 拒絕執(zhí)行任務(wù)方法登夫,當(dāng)線程池在一些場景中广匙,不能處理新加入的線程時,會通過該對象處理拒絕策略恼策;
   
6鸦致、final void runWorker(Worker w)
   // 該方法被Worker工作線程的run方法調(diào)用,真正核心處理Runable任務(wù)的方法

7涣楷、private static int runStateOf(int c)     { return c & ~CAPACITY; }
   // c & 高3位為1分唾,低29位為0的~CAPACITY,用于獲取高3位保存的線程池狀態(tài)
   
8狮斗、public void shutdown()
   // 不會立即終止線程池绽乔,而是要等所有任務(wù)緩存隊列中的任務(wù)都執(zhí)行完后才終止,但再也不會接受新的任務(wù)

9碳褒、public List<Runnable> shutdownNow()
   // 立即終止線程池折砸,并嘗試打斷正在執(zhí)行的任務(wù),并且清空任務(wù)緩存隊列沙峻,返回尚未執(zhí)行的任務(wù)
   
10睦授、private void processWorkerExit(Worker w, boolean completedAbruptly)
   // worker線程退出   

三、源碼分析

3.1摔寨、execute

1去枷、execute源碼:
   /**
     * Executes the given task sometime in the future.  The task
     * may execute in a new thread or in an existing pooled thread.
     *
     * If the task cannot be submitted for execution, either because this
     * executor has been shutdown or because its capacity has been reached,
     * the task is handled by the current {@code RejectedExecutionHandler}.
     *
     * @param command the task to execute
     * @throws RejectedExecutionException at discretion of
     *         {@code RejectedExecutionHandler}, if the task
     *         cannot be accepted for execution
     * @throws NullPointerException if {@code command} is null
     */
    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(); // 獲取原子計數(shù)值最新值
        if (workerCountOf(c) < corePoolSize) { // 判斷當(dāng)前線程池數(shù)量是否小于核心線程數(shù)量
            if (addWorker(command, true)) // 嘗試添加command任務(wù)到核心線程
                return;
            c = ctl.get(); // 重新獲取當(dāng)前線程池狀態(tài)值,為后面的檢查做準(zhǔn)備。
        }
        // 執(zhí)行到此删顶,說明核心線程任務(wù)數(shù)量已滿竖螃,新添加的線程入等待隊列,這個熟練是大于corePoolSize且小于maximumPoolSize
        if (isRunning(c) && workQueue.offer(command)) { // 如果線程池處于可接受任務(wù)狀態(tài)翼闹,嘗試添加到等待隊列
            int recheck = ctl.get(); // 雙重校驗
            if (! isRunning(recheck) && remove(command)) // 如果線程池突然不可接受任務(wù)斑鼻,則嘗試移除該command任務(wù)
                reject(command); // 不可接受任務(wù)且成功從等待隊列移除任務(wù),則執(zhí)行拒絕策略操作猎荠,通過策略告訴調(diào)用方任務(wù)入隊情況
            else if (workerCountOf(recheck) == 0) // 如果此刻線程數(shù)量為0的話將沒有Worker執(zhí)行新的task坚弱,所以增加一個Worker
                addWorker(null, false); // 添加一個Worker
        }
        // 執(zhí)行到此,說明添加任務(wù)等待隊列已滿关摇,所以嘗試添加一個Worker
        else if (!addWorker(command, false)) // 如果添加失敗的話荒叶,那么拒絕此線程任務(wù)添加
            reject(command); // 拒絕此線程任務(wù)添加
    }
    
2、小結(jié):
    ? 如果線程池中的線程數(shù)量 < corePoolSize输虱,就創(chuàng)建新的線程來執(zhí)行新添加的任務(wù)些楣;
    ? 如果線程池中的線程數(shù)量 >= corePoolSize,但隊列workQueue未滿宪睹,則將新添加的任務(wù)放到workQueue中愁茁;
    ? 如果線程池中的線程數(shù)量 >= corePoolSize,且隊列workQueue已滿亭病,但線程池中的線程數(shù)量 < maximumPoolSize鹅很,則會創(chuàng)建新的線程來處理被添加的任務(wù);
    ? 如果線程池中的線程數(shù)量 = maximumPoolSize罪帖,就用RejectedExecutionHandler來執(zhí)行拒絕策略促煮;

3.2、addWorker

1整袁、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) {
        retry: // 外層循環(huán)菠齿,負責(zé)判斷線程池狀態(tài),處理線程池狀態(tài)變量加1操作
        for (;;) {
            int c = ctl.get();
            int rs = runStateOf(c); // 讀取狀態(tài)值

            // Check if queue empty only if necessary.
            // 滿足下面兩大條件的坐昙,說明線程池不能接受任務(wù)了绳匀,直接返回false處理
            // 主要目的就是想說,只有線程池的狀態(tài)為 RUNNING 狀態(tài)時民珍,線程池才會接收新的任務(wù)襟士,增加新的Worker工作線程
            if (rs >= SHUTDOWN && // 線程池的狀態(tài)已經(jīng)至少已經(jīng)處于不能接收任務(wù)的狀態(tài)了,目的是檢查線程池是否處于關(guān)閉狀態(tài)
                ! (rs == SHUTDOWN &&
                   firstTask == null &&
                   ! workQueue.isEmpty()))
                return false;

            // 內(nèi)層循環(huán)嚷量,負責(zé)worker數(shù)量加1操作
            for (;;) {
                int wc = workerCountOf(c); // 獲取當(dāng)前worker線程數(shù)量
                if (wc >= CAPACITY || // 如果線程池數(shù)量達到最大上限值CAPACITY
                    // core為true時判斷是否大于corePoolSize核心線程數(shù)量
                    // core為false時判斷是否大于maximumPoolSize最大設(shè)置的線程數(shù)量
                    wc >= (core ? corePoolSize : maximumPoolSize)) 
                    return false;
                    
                // 調(diào)用CAS原子操作陋桂,目的是worker線程數(shù)量加1
                if (compareAndIncrementWorkerCount(c)) // 
                    break retry;
                    
                c = ctl.get();  // Re-read ctl // CAS原子操作失敗的話,則再次讀取ctl值
                if (runStateOf(c) != rs) // 如果剛剛讀取的c狀態(tài)不等于先前讀取的rs狀態(tài)蝶溶,則繼續(xù)外層循環(huán)判斷
                    continue retry;
                // else CAS failed due to workerCount change; retry inner loop
                // 之所以會CAS操作失敗嗜历,主要是由于多線程并發(fā)操作宣渗,導(dǎo)致workerCount工作線程數(shù)量改變而導(dǎo)致的,因此繼續(xù)內(nèi)層循環(huán)嘗試操作
            }
        }

        boolean workerStarted = false;
        boolean workerAdded = false;
        Worker w = null;
        try {
            // 創(chuàng)建一個Worker工作線程對象梨州,將任務(wù)firstTask痕囱,新創(chuàng)建的線程thread都封裝到了Worker對象里面
            w = new Worker(firstTask);
            final Thread t = w.thread;
            if (t != null) {
                // 由于對工作線程集合workers的添加或者刪除,涉及到線程安全問題暴匠,所以才加上鎖且該鎖為非公平鎖
                final ReentrantLock mainLock = this.mainLock;
                mainLock.lock();
                try {
                    // Recheck while holding lock.
                    // Back out on ThreadFactory failure or if
                    // shut down before lock acquired.
                    // 獲取鎖成功后鞍恢,執(zhí)行臨界區(qū)代碼,首先檢查獲取當(dāng)前線程池的狀態(tài)rs
                    int rs = runStateOf(ctl.get());

                    // 當(dāng)線程池處于可接收任務(wù)狀態(tài)
                    // 或者是不可接收任務(wù)狀態(tài)每窖,但是有可能該任務(wù)等待隊列中的任務(wù)
                    // 滿足這兩種條件時帮掉,都可以添加新的工作線程
                    if (rs < SHUTDOWN ||
                        (rs == SHUTDOWN && firstTask == null)) {
                        if (t.isAlive()) // precheck that t is startable
                            throw new IllegalThreadStateException();
                        workers.add(w); // 添加新的工作線程到工作線程集合workers,workers是set集合
                        int s = workers.size();
                        if (s > largestPoolSize) // 變量記錄了線程池在整個生命周期中曾經(jīng)出現(xiàn)的最大線程個數(shù)
                            largestPoolSize = s;
                        workerAdded = true;
                    }
                } finally {
                    mainLock.unlock();
                }
                if (workerAdded) { // 往workers工作線程集合中添加成功后窒典,則立馬調(diào)用線程start方法啟動起來
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted) // 如果啟動線程失敗的話蟆炊,還得將剛剛添加成功的線程共集合中移除并且做線程數(shù)量做減1操作
                addWorkerFailed(w);
        }
        return workerStarted;
    }
    
2、小結(jié):
    ? 該方法是任務(wù)提交的一個核心方法瀑志,主要完成狀態(tài)的檢查涩搓,工作線程的創(chuàng)建并添加到線程集合切最后順利的話將創(chuàng)建的線程啟動;
    ? addWorker(command, true):當(dāng)線程數(shù)小于corePoolSize時劈猪,添加一個需要處理的任務(wù)command進線程集合昧甘,如果workers數(shù)量超過corePoolSize時,則返回false不需要添加工作線程战得;
    ? addWorker(command, false):當(dāng)?shù)却犃幸褲M時疾层,將新來的任務(wù)command添加到workers線程集合中去,若線程集合大小超過maximumPoolSize時贡避,則返回false不需要添加工作線程;
    ? addWorker(null, false):放一個空的任務(wù)進線程集合予弧,當(dāng)這個空任務(wù)的線程執(zhí)行時刮吧,會從等待任務(wù)隊列中通過getTask獲取任務(wù)再執(zhí)行,創(chuàng)建新線程且沒有任務(wù)分配掖蛤,當(dāng)執(zhí)行時才去取任務(wù)杀捻;
    ? addWorker(null, true):創(chuàng)建空任務(wù)的工作線程到workers集合中去,在setCorePoolSize方法調(diào)用時目的是初始化核心工作線程實例蚓庭;

3.3致讥、runWorker

1、runWorker源碼:
    /**
     * Main worker run loop.  Repeatedly gets tasks from queue and
     * executes them, while coping with a number of issues:
     *
     * 1. We may start out with an initial task, in which case we
     * don't need to get the first one. Otherwise, as long as pool is
     * running, we get tasks from getTask. If it returns null then the
     * worker exits due to changed pool state or configuration
     * parameters.  Other exits result from exception throws in
     * external code, in which case completedAbruptly holds, which
     * usually leads processWorkerExit to replace this thread.
     *
     * 2. Before running any task, the lock is acquired to prevent
     * other pool interrupts while the task is executing, and then we
     * ensure that unless pool is stopping, this thread does not have
     * its interrupt set.
     *
     * 3. Each task run is preceded by a call to beforeExecute, which
     * might throw an exception, in which case we cause thread to die
     * (breaking loop with completedAbruptly true) without processing
     * the task.
     *
     * 4. Assuming beforeExecute completes normally, we run the task,
     * gathering any of its thrown exceptions to send to afterExecute.
     * We separately handle RuntimeException, Error (both of which the
     * specs guarantee that we trap) and arbitrary Throwables.
     * Because we cannot rethrow Throwables within Runnable.run, we
     * wrap them within Errors on the way out (to the thread's
     * UncaughtExceptionHandler).  Any thrown exception also
     * conservatively causes thread to die.
     *
     * 5. After task.run completes, we call afterExecute, which may
     * also throw an exception, which will also cause thread to
     * die. According to JLS Sec 14.20, this exception is the one that
     * will be in effect even if task.run throws.
     *
     * The net effect of the exception mechanics is that afterExecute
     * and the thread's UncaughtExceptionHandler have as accurate
     * information as we can provide about any problems encountered by
     * user code.
     *
     * @param w the worker
     */
    final void runWorker(Worker w) {
        Thread wt = Thread.currentThread();
        Runnable task = w.firstTask;
        w.firstTask = null;
        w.unlock(); // allow interrupts 允許中斷
        boolean completedAbruptly = true;
        try {
            // 不斷從等待隊列blockingQueue中獲取任務(wù)
            // 之前addWorker(null, false)這樣的線程執(zhí)行時器赞,會通過getTask中再次獲取任務(wù)并執(zhí)行
            while (task != null || (task = getTask()) != null) {
                w.lock(); // 上鎖垢袱,并不是防止并發(fā)執(zhí)行任務(wù),而是為了防止shutdown()被調(diào)用時不終止正在運行的worker線程
                // If pool is stopping, ensure thread is interrupted;
                // if not, ensure thread is not interrupted.  This
                // requires a recheck in second case to deal with
                // shutdownNow race while clearing interrupt
                if ((runStateAtLeast(ctl.get(), STOP) ||
                     (Thread.interrupted() &&
                      runStateAtLeast(ctl.get(), STOP))) &&
                    !wt.isInterrupted())
                    wt.interrupt();
                try {
                    // task.run()執(zhí)行前港柜,由子類實現(xiàn)
                    beforeExecute(wt, task);
                    Throwable thrown = null;
                    try {
                        task.run(); // 執(zhí)行線程Runable的run方法
                    } catch (RuntimeException x) {
                        thrown = x; throw x;
                    } catch (Error x) {
                        thrown = x; throw x;
                    } catch (Throwable x) {
                        thrown = x; throw new Error(x);
                    } finally {
                        // task.run()執(zhí)行后请契,由子類實現(xiàn)
                        afterExecute(task, thrown);
                    }
                } finally {
                    task = null;
                    w.completedTasks++;
                    w.unlock();
                }
            }
            completedAbruptly = false;
        } finally {
            processWorkerExit(w, completedAbruptly);
        }
    }

2咳榜、小結(jié):
    ? addWorker通過調(diào)用t.start()啟動了線程,線程池的真正核心執(zhí)行任務(wù)的地方就在此runWorker中爽锥;
    ? 不斷的執(zhí)行我們提交任務(wù)的run方法涌韩,可能是剛剛提交的任務(wù),可能是隊列中等待的隊列氯夷,原因在于Worker工作線程類繼承了AQS類臣樱;
    ? Worker重寫了AQS的tryAcquire方法,不管先來后到腮考,一種非公平的競爭機制雇毫,通過CAS獲取鎖,獲取到了就執(zhí)行代碼塊秸仙,沒獲取到的話則添加到CLH隊列中通過利用LockSuporrt的park/unpark阻塞任務(wù)等待嘴拢;
    ? addWorker通過調(diào)用t.start()啟動了線程,線程池的真正核心執(zhí)行任務(wù)的地方就在此runWorker中寂纪;

3.processWorkerExit

1席吴、processWorkerExit源碼:
    /**
     * Performs cleanup and bookkeeping for a dying worker. Called
     * only from worker threads. Unless completedAbruptly is set,
     * assumes that workerCount has already been adjusted to account
     * for exit.  This method removes thread from worker set, and
     * possibly terminates the pool or replaces the worker if either
     * it exited due to user task exception or if fewer than
     * corePoolSize workers are running or queue is non-empty but
     * there are no workers.
     *
     * @param w the worker
     * @param completedAbruptly if the worker died due to user exception
     */
    private void processWorkerExit(Worker w, boolean completedAbruptly) {
        // 如果突然中止,說明runWorker中遇到什么異常了捞蛋,那么正在工作的線程自然就需要減1操作了
        if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted
            decrementWorkerCount();

        final ReentrantLock mainLock = this.mainLock;
        // 執(zhí)行到此孝冒,說明runWorker正常執(zhí)行完了,需要正常退出工作線程拟杉,上鎖正常操作移除線程
        mainLock.lock();
        try {
            completedTaskCount += w.completedTasks; // 增加線程池完成任務(wù)數(shù)
            workers.remove(w); // 從workers線程集合中移除已經(jīng)工作完的線程
        } finally {
            mainLock.unlock();
        }

        // 在對線程池有負效益的操作時庄涡,都需要“嘗試終止”線程池,主要是判斷線程池是否滿足終止的狀態(tài)搬设;
        // 如果狀態(tài)滿足穴店,但還有線程池還有線程,嘗試對其發(fā)出中斷響應(yīng)拿穴,使其能進入退出流程泣洞;
        // 沒有線程了,更新狀態(tài)為tidying->terminated默色;
        tryTerminate();

        int c = ctl.get();
        
        // 如果狀態(tài)是running球凰、shutdown,即tryTerminate()沒有成功終止線程池腿宰,嘗試再添加一個worker
        if (runStateLessThan(c, STOP)) {
            // 不是突然完成的呕诉,即沒有task任務(wù)可以獲取而完成的,計算min吃度,并根據(jù)當(dāng)前worker數(shù)量判斷是否需要addWorker()
            if (!completedAbruptly) {
                int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
                
                // 如果min為0甩挫,且workQueue不為空,至少保持一個線程
                if (min == 0 && ! workQueue.isEmpty())
                    min = 1;
                    
                // 如果線程數(shù)量大于最少數(shù)量椿每,直接返回捶闸,否則下面至少要addWorker一個
                if (workerCountOf(c) >= min)
                    return; // replacement not needed
            }
            
            // 只要worker是completedAbruptly突然終止的夜畴,或者線程數(shù)量小于要維護的數(shù)量,就新添一個worker線程删壮,即使是shutdown狀態(tài)
            addWorker(null, false);
        }
    }

2贪绘、小結(jié):
    ? 異常中止情況worker數(shù)量減1,正常情況就上鎖從workers中移除央碟;
    ? tryTerminate():在對線程池有負效益的操作時税灌,都需要“嘗試終止”線程池;
    ? 是否需要增加worker線程,如果線程池還沒有完全終止亿虽,仍需要保持一定數(shù)量的線程; 

四菱涤、一些建議

4.1、合理配置線程池的大小(僅供參考)

1洛勉、如果是CPU密集型任務(wù)粘秆,就需要盡量壓榨CPU,參考值可以設(shè)為 NCPU+1收毫;
2攻走、如果是IO密集型任務(wù),參考值可以設(shè)置為2*NCPU此再;

4.2昔搂、JDK幫助文檔建議

“強烈建議程序員使用較為方便的Executors工廠方法:

五、下載地址

https://gitee.com/ylimhhmily/SpringCloudTutorial.git

SpringCloudTutorial交流QQ群: 235322432

SpringCloudTutorial交流微信群: 微信溝通群二維碼圖片鏈接

歡迎關(guān)注输拇,您的肯定是對我最大的支持!!!

<上一篇????????首頁????????下一篇>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末摘符,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子策吠,更是在濱河造成了極大的恐慌逛裤,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,372評論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件猴抹,死亡現(xiàn)場離奇詭異别凹,居然都是意外死亡,警方通過查閱死者的電腦和手機洽糟,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來堕战,“玉大人坤溃,你說我怎么就攤上這事≈龆” “怎么了薪介?”我有些...
    開封第一講書人閱讀 162,415評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長越驻。 經(jīng)常有香客問我汁政,道長道偷,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,157評論 1 292
  • 正文 為了忘掉前任记劈,我火速辦了婚禮勺鸦,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘目木。我一直安慰自己换途,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,171評論 6 388
  • 文/花漫 我一把揭開白布刽射。 她就那樣靜靜地躺著军拟,像睡著了一般。 火紅的嫁衣襯著肌膚如雪誓禁。 梳的紋絲不亂的頭發(fā)上懈息,一...
    開封第一講書人閱讀 51,125評論 1 297
  • 那天,我揣著相機與錄音摹恰,去河邊找鬼辫继。 笑死,一個胖子當(dāng)著我的面吹牛戒祠,可吹牛的內(nèi)容都是我干的骇两。 我是一名探鬼主播,決...
    沈念sama閱讀 40,028評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼姜盈,長吁一口氣:“原來是場噩夢啊……” “哼低千!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起馏颂,我...
    開封第一講書人閱讀 38,887評論 0 274
  • 序言:老撾萬榮一對情侶失蹤示血,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后救拉,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體难审,經(jīng)...
    沈念sama閱讀 45,310評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,533評論 2 332
  • 正文 我和宋清朗相戀三年亿絮,在試婚紗的時候發(fā)現(xiàn)自己被綠了告喊。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,690評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡派昧,死狀恐怖黔姜,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情蒂萎,我是刑警寧澤秆吵,帶...
    沈念sama閱讀 35,411評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站五慈,受9級特大地震影響纳寂,放射性物質(zhì)發(fā)生泄漏主穗。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,004評論 3 325
  • 文/蒙蒙 一毙芜、第九天 我趴在偏房一處隱蔽的房頂上張望忽媒。 院中可真熱鬧,春花似錦爷肝、人聲如沸猾浦。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽金赦。三九已至,卻和暖如春对嚼,著一層夾襖步出監(jiān)牢的瞬間夹抗,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評論 1 268
  • 我被黑心中介騙來泰國打工纵竖, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留漠烧,地道東北人。 一個月前我還...
    沈念sama閱讀 47,693評論 2 368
  • 正文 我出身青樓靡砌,卻偏偏與公主長得像已脓,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子通殃,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,577評論 2 353

推薦閱讀更多精彩內(nèi)容