老熟女激烈的高潮_日韩一级黄色录像_亚洲1区2区3区视频_精品少妇一区二区三区在线播放_国产欧美日产久久_午夜福利精品导航凹凸

重慶分公司,新征程啟航

為企業提供網站建設、域名注冊、服務器等服務

Java的線程池的工作原理

本篇內容主要講解“Java的線程池的工作原理”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Java的線程池的工作原理”吧!

讓客戶滿意是我們工作的目標,不斷超越客戶的期望值來自于我們對這個行業的熱愛。我們立志把好的技術通過有效、簡單的方式提供給客戶,將通過不懈努力成為客戶在信息化領域值得信任、有價值的長期合作伙伴,公司提供的服務項目有:域名注冊、網頁空間、營銷軟件、網站建設、謝家集網站維護、網站推廣。

?? 前提概要

相信大家都用過線程池,對該類ThreadPoolExecutor應該一點都不陌生了

  1. 我們之所以要用到線程池,線程池主要用來解決線程生命周期開銷問題和資源不足問題

  2. 我們通過對多個任務重用線程以及控制線程池的數目可以有效防止資源不足的情況

  3. 本章節就著重和大家分享分析一下JDK8的ThreadPoolExecutor核心類,看看線程池是如何工作的

?? 核心原理

線程池在內部實際上構建了一個生產者消費者模型,將任務的提交和任務執行兩者解耦,并不直接關聯,從而良好的緩沖任務,復用線程。

線程池的運行主要分成兩部分任務管理、線程管理。

?? 任務管理

任務管理充當生產者的角色

  • 當任務提交后,線程池會判斷該任務后續的流轉

  • 直接申請線程執行該任務

  • 緩沖到隊列中等待線程執行

  • 拒絕該任務。

?? 線程管理

線程管理是消費者的角色

  • 它們被統一維護在線程池內,根據任務請求進行線程的分配

  • 當線程執行完任務后則會繼續獲取新的任務去執行,

  • 最終當線程獲取不到任務的時候,線程就會被回收。

接下來,我們會按照以下三個部分去詳細講解線程池運行機制:

  1. 線程池如何維護自身狀態

  2. 線程池如何管理任務

  3. 線程池如何管理線程

?? 構造器

?? 四個構造器
	// 構造器一
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
        Executors.defaultThreadFactory(), defaultHandler);
    }


	// 構造器二
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue workQueue,
                              ThreadFactory threadFactory) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             threadFactory, defaultHandler);
    }

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

	// 構造器四
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue 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;
    }

通過仔細查看構造器代碼,發現最終都是調用構造器四,緊接著賦值了一堆的字段,接下來我們先看看這些字段是什么含義;

  • corePoolSize:核心運行的線程池數量大小,當線程數量超過該值時,就需要將超過該數量值的線程放到等待隊列中;

  • maximumPoolSize:線程池最大能容納的線程數(該數量已經包含了corePoolSize數量),當線程數量超過該值時,則會拒絕執行處理策略;

  • workQueue:等待隊列,當達到corePoolSize的時候,就將新加入的線程追加到workQueue該等待隊列中;當然BlockingQueue類也是一個抽象類,也有很多子類來實現不同的隊列等待, 一般來說,阻塞隊列有一下幾種:

    • ArrayBlockingQueue

    • LinkedBlockingQueue

    • SynchronousQueue

    • DelayedWorkQueue

    • ArrayBlockingQueue,PriorityBlockingQueue使用較少,一般使用LinkedBlockingQueue和Synchronous

  • keepAliveTime:表示線程沒有任務執行時最多保持多久存活時間

    • 默認情況下當線程數量大于corePoolSize后keepAliveTime才會起作用,并生效,一旦線程池的數量小于corePoolSize后keepAliveTime又不起作用了;

    • 但是如果調用了 allowCoreThreadTimeOut(boolean)方法,在線程池中的線程數不大于corePoolSize時,keepAliveTime參數也會起作用,直到線程池中的線程數為0

  • threadFactory:新創建線程出生的地方

  • handler拒絕執行處理抽象類,就是說當線程池在一些場景中,不能處理新加入的線程任務時,會通過該對象處理拒絕策略

    • 策略一( CallerRunsPolicy ):只要線程池沒關閉,就直接用調用者所在線程來運行任務;

    • 策略二( AbortPolicy ):默認策略,直接拋出RejectedExecutionException異常

    • 策略三( DiscardPolicy ):執行空操作,什么也不干,拒絕任務后也不做任何回應

    • 策略四( DiscardOldestPolicy ):將隊列中存活最久的那個未執行的任務拋棄掉,然后將當前新的線程放進去(LRU);

    • 該對象RejectedExecutionHandler有四個實現類,即四種策略,讓我們有選擇性的在什么場景下該怎么使用拒絕策略;

  • largestPoolSize:變量記錄了線程池在整個生命周期中曾經出現的最大線程個數

  • allowCoreThreadTimeOut:當為true時,核心線程也有超時退出的概念一說


線程池的生命周期

線程池運行的狀態,并不是用戶顯式設置的,而是伴隨著線程池的運行,由內部來維護。

線程池內部使用一個變量維護兩個值:運行狀態(runState)和線程數量 (workerCount),兩個關鍵參數的維護放在了一起。

private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
  • ctl這個AtomicInteger類型,是對線程池的運行狀態和線程池中有效線程的數量進行控制的一個字段。

  • 原子變量值,是一個復核類型的成員變量,是一個原子整數,借助高低位包裝了兩個概念,它同時包含兩部分的信息:線程池的運行狀態 (runState) 和線程池內有效線程的數量 (workerCount),高3位保存runState,低29位保存workerCount,兩個變量之間互不干擾。

    • 用一個變量去存儲兩個值,可避免在做相關決策時,出現不一致的情況,不必為了維護兩者的一致,而占用鎖資源

    • 線程池也提供了若干方法去供用戶獲得線程池當前的運行狀態、線程個數。這里都使用的是位運算的方式,相比于基本運算,速度也會快很多。

關于內部封裝的獲取生命周期狀態、獲取線程池線程數量的計算方法如以下代碼所示:

// 偏移位數,常量值29,之所以偏移29,目的是將32位的原子變量值ctl的高3位設置為
// 線程池的狀態,低29位作為線程池大小數量值;32-3

private static final int COUNT_BITS = Integer.SIZE - 3;

//低29位都為1,高位都為0
// 線程池的最大容量值
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;//111
 // 不接受新任務,但會處理隊列任務
private static final int SHUTDOWN   =  0 << COUNT_BITS;//000
// 不接受新任務,不會處理隊列任務,而且會中斷正在處理過程中的任務
private static final int STOP       =  1 << COUNT_BITS;//001
// 所有的任務已結束,workerCount為0,線程過渡到TIDYING狀態,將會執行terminated()鉤子方法
private static final int TIDYING    =  2 << COUNT_BITS;//010
 // terminated()方法已經完成
private static final int TERMINATED =  3 << COUNT_BITS;//011

// Packing and unpacking ctl線程池的狀態,原子變量值ctl的高三位
//計算當前運行狀態,取高三位
private static int runStateOf(int c)     { return c & ~CAPACITY; }

//計算當前線程數量,取低29位
private static int workerCountOf(int c)  { return c & CAPACITY; }

//通過狀態和線程數生成ctl
private static int ctlOf(int rs, int wc) { return rs | wc; }

HashSet workers = new HashSet();
 // 存放工作線程的線程池;

ThreadPoolExecutor的運行狀態有5種,分別為:

Java的線程池的工作原理


Java的線程池的工作原理

成員方法

   // 提交任務,添加Runnable對象到線程池,由線程池調度執行
public void execute(Runnable command)

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

// 添加worker工作線程,根據邊界值來決定是否創建新的線程
private boolean addWorker(Runnable firstTask, boolean core)

// c通常一般為ctl,ctl值小于0,則處于可以接受新任務狀態
private static boolean isRunning(int c)

// 拒絕執行任務方法,當線程池在一些場景中,不能處理新加入的線程時,會通過該對象處理拒絕策略;
final void reject(Runnable command)

// 該方法被Worker工作線程的run方法調用,真正核心處理Runnable任務的方法
final void runWorker(Worker w)

// c & 高3位為1,低29位為0的~CAPACITY,用于獲取高3位保存的線程池狀態
private static int runStateOf(int c)     { return c & ~CAPACITY; }

// 不會立即終止線程池,而是要等所有任務緩存隊列中的任務都執行完后才終止,但再也不會接受新的任務 void shutdown()
public void shutdown()

// 立即終止線程池,并嘗試打斷正在執行的任務,并且清空任務緩存隊列,返回尚未執行的任務
public List shutdownNow()

// worker線程退出
private void processWorkerExit(Worker w, boolean completedAbruptly)

源碼分析

首先,所有任務的調度都是由execute方法完成的,這部分完成的工作是:檢查現在線程池的運行狀態、運行線程數、運行策略,決定接下來執行的流程,是直接申請線程執行,或是緩沖到隊列中執行,亦或是直接拒絕該任務。其執行過程如下:


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(); // 獲取原子計數值最新值
        if (workerCountOf(c) < corePoolSize) {
		// 判斷當前線程池數量是否小于核心線程數量
            if (addWorker(command, true)) 
			// 嘗試添加command任務到核心線程
                return;
                c = ctl.get();
			 // 重新獲取當前線程池狀態值,為后面的檢查做準備。
        }
		// 執行到此,說明核心線程任務數量已滿,新添加的線程入等待隊列,
		這個是大于corePoolSize且小于maximumPoolSize
        if (isRunning(c) && workQueue.offer(command)) { 
		   // 如果線程池處于可接受任務狀態,嘗試添加到等待隊列
            int recheck = ctl.get(); // 雙重校驗
            if (! isRunning(recheck) && remove(command)) 
			 // 如果線程池突然不可接受任務,則嘗試移除該command任務
                reject(command); 
				// 不可接受任務且成功從等待隊列移除任務,則執行拒絕策略操作,
				// 通過策略告訴調用方任務入隊情況
            else if (workerCountOf(recheck) == 0) 
			// 如果此刻線程數量為0的話將沒有Worker執行新的task,所以增加一個Worker
                addWorker(null, false); 
				// 添加一個Worker
        }
		// 執行到此,說明添加任務等待隊列已滿,所以嘗試添加一個Worker
        else if (!addWorker(command, false))
		  // 如果添加失敗的話,那么拒絕此線程任務添加
		  // 拒絕此線程任務添加
            reject(command);
    }
小結:
  1. 首先檢測線程池運行狀態,如果不是RUNNING,則直接拒絕,線程池要保證在RUNNING的狀態下執行任務。

  2. 如果workerCount < corePoolSize,則創建并啟動一個線程來執行新提交的任務。

  3. 如果workerCount >= corePoolSize,且線程池內的阻塞隊列未滿,則將任務添加到該阻塞隊列中。

  4. 如果workerCount >= corePoolSize && workerCount < maximumPoolSize,且線程池內的阻塞隊列已滿,則創建并啟動一個線程來執行新提交的任務。

  5. 如果workerCount >= maximumPoolSize,并且線程池內的阻塞隊列已滿, 則根據拒絕策略來處理該任務, 默認的處理方式是直接拋異常。就用RejectedExecutionHandler來執行拒絕策略;

Java的線程池的工作原理

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) {
     	// 外層循環,負責判斷線程池狀態,處理線程池狀態變量加1操作
        retry:
        for (;;) {
		    // 狀態總體相關值:運行狀態 + 執行線程任務數量 
            int c = ctl.get();
			// 讀取狀態值 - 運行狀態
            int rs = runStateOf(c);
            // Check if queue empty only if necessary.
			// 滿足下面兩大條件的,說明線程池不能接受任務了,直接返回false處理
			// 主要目的就是想說,只有線程池的狀態為 RUNNING 狀態時,線程池才會接收
			// 新的任務,增加新的Worker工作線程
			// 線程池的狀態已經至少已經處于不能接收任務的狀態了
            if (rs >= SHUTDOWN &&
			  //目的是檢查線 程池是否處于關閉狀態
                ! (rs == SHUTDOWN && firstTask == null && ! workQueue.isEmpty()))
                       return false;
				// 內層循環,負責worker數量加1操作
				for (;;) {
				// 獲取當前worker線程數量
					int wc = workerCountOf(c);
					if (wc >= CAPACITY ||
						// 如果線程池數量達到最大上限值CAPACITY
						// core為true時判斷是否大于corePoolSize核心線程數量
						// core為false時判斷是否大于maximumPoolSize最大設置的線程數量
						wc >= (core ? corePoolSize : maximumPoolSize))
						return false;
					// 調用CAS原子操作,目的是worker線程數量加1
					if (compareAndIncrementWorkerCount(c)) //
						break retry;
					c = ctl.get();  // Re-read ctl
					// CAS原子操作失敗的話,則再次讀取ctl值
					if (runStateOf(c) != rs)
					// 如果剛剛讀取的c狀態不等于先前讀取的rs狀態,則繼續外層循環判斷
						continue retry;
					// else CAS failed due to workerCount change; retry inner loop
					// 之所以會CAS操作失敗,主要是由于多線程并發操作,導致workerCount
					// 工作線程數量改變而導致的,因此繼續內層循環嘗試操作
				}
        }
        boolean workerStarted = false;
        boolean workerAdded = false;
        Worker w = null;
        try {
			// 創建一個Worker工作線程對象,將任務firstTask,
			// 新創建的線程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.
					// 獲取鎖成功后,執行臨界區代碼,首先檢查獲取當前線程池的狀態rs
                    int rs = runStateOf(ctl.get());
					// 當線程池處于可接收任務狀態
					// 或者是不可接收任務狀態,但是有可能該任務等待隊列中的任務
					// 滿足這兩種條件時,都可以添加新的工作線程
                    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) 
						// 變量記錄了線程池在整個生命周期中曾經出現的最大線程個數
                            largestPoolSize = s;
                        workerAdded = true;
                    }
                } finally {
                    mainLock.unlock();
                }
                if (workerAdded) { 
				// 往workers工作線程集合中添加成功后,則立馬調用線程start方法啟動起來
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
			// 如果啟動線程失敗的話,還得將剛剛添加成功的線程共集合中移除并且做線				// 程數量做減1操作
                addWorkerFailed(w);
        }
        return workerStarted;
    }
小結:
  • 該方法是任務提交的一個核心方法,主要完成狀態的檢查,工作線程的創建并添加到線程集合切最后順利的話將創建的線程啟動

  • addWorker(command, true):當線程數小于corePoolSize時,添加一個需要處理的任務command進線程集合,如果workers數量超過corePoolSize時,則返回false不需要添加工作線程;

  • addWorker(command, false):當等待隊列已滿時,將新來的任務command添加到workers線程集合中去,若線程集合大小超過maximumPoolSize時,則返回false不需要添加工作線程;

  • addWorker(null, false):放一個空的任務進線程集合,當這個空任務的線程執行時,會從等待任務隊列中通過getTask獲取任務再執行,創建新線程且沒有任務分配,當執行時才去取任務;

  • addWorker(null, true):創建空任務的工作線程到workers集合中去,在setCorePoolSize方法調用時目的是初始化核心工作線程實例

任務調度機制

任務調度是線程池的主要入口,當用戶提交了一個任務,接下來這個任務將如何執行都是由這個階段決定的。了解這部分就相當于了解了線程池的核心運行機制。

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;
		// allow interrupts 允許中斷
        w.unlock();
        boolean completedAbruptly = true;
        try {
			// 不斷從等待隊列blockingQueue中獲取任務
			// 之前addWorker(null, false)這樣的線程執行時,
			// 會通過getTask中再次獲取任務并執行
            while (task != null || (task = getTask()) != null) {
                w.lock(); 
				// 上鎖,并不是防止并發執行任務,
				// 而是為了防止shutdown()被調用時不終止正在運行的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()執行前,由子類實現
                    beforeExecute(wt, task);
                    Throwable thrown = null;
                    try {
                        task.run(); // 執行線程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()執行后,由子類實現
                        afterExecute(task, thrown);
                    }
                } finally {
                    task = null;
                    w.completedTasks++;
                    w.unlock();
                }
            }
            completedAbruptly = false;
        } finally {
            processWorkerExit(w, completedAbruptly);
        }
    }

小結

  • addWorker通過調用t.start()啟動了線程,線程池的真正核心執行任務的地方就在此runWorker中

  • 不斷的執行我們提交任務的run方法,可能是剛剛提交的任務,可能是隊列中等待的隊列,原因在于Worker工作線程類繼承了AQS類

  • Worker重寫了AQS的tryAcquire方法,不管先來后到,一種非公平的競爭機制,通過CAS獲取鎖,獲取到了就執行代碼塊,沒獲取到的話則添加到CLH隊列中通過利用LockSuporrt的park/unpark阻塞任務等待

  • addWorker通過調用t.start()啟動了線程,線程池的真正核心執行任務的地方就在此runWorker中

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;
		// 執行到此,說明runWorker正常執行完了,
		// 需要正常退出工作線程,上鎖正常操作移除線程
        mainLock.lock();
        try {
            completedTaskCount += w.completedTasks; // 增加線程池完成任務數
            workers.remove(w);  // 從workers線程集合中移除已經工作完的線程
        } finally {
            mainLock.unlock();
        }
		// 在對線程池有負效益的操作時,都需要“嘗試終止”線程池,主要是判斷線程池是否滿足終止的狀態;
		// 如果狀態滿足,但還有線程池還有線程,嘗試對其發出中斷響應,使其能進入退出流程;
		// 沒有線程了,更新狀態為tidying->terminated;
        tryTerminate();
        int c = ctl.get();
		// 如果狀態是running、shutdown,即tryTerminate()沒有成功終止線程池,嘗試再添加一個worker
        if (runStateLessThan(c, STOP)) {
			// 不是突然完成的,即沒有task任務可以獲取而完成的,計算min,并根據當前worker數量判斷是否需要addWorker()
            if (!completedAbruptly) {
                int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
				
				// 如果min為0,且workQueue不為空,至少保持一個線程
                if (min == 0 && ! workQueue.isEmpty())
                    min = 1;
					
				// 如果線程數量大于最少數量,直接返回,否則下面至少要addWorker一個
                if (workerCountOf(c) >= min)
                    return; // replacement not needed
            }
			
// 只要worker是completedAbruptly突然終止的,或者線程數量小于要維護的數量,就新添一個worker線程,即使是shutdown狀態
            addWorker(null, false);
        }
 }

小結:

  • 異常中止情況worker數量減1,正常情況就上鎖從workers中移除;

  • tryTerminate():在對線程池有負效益的操作時,都需要“嘗試終止”線程池;

  • 是否需要增加worker線程,如果線程池還沒有完全終止,仍需要保持一定數量的線程;

到此,相信大家對“Java的線程池的工作原理”有了更深的了解,不妨來實際操作一番吧!這里是創新互聯網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!


文章題目:Java的線程池的工作原理
文章路徑:http://www.xueling.net.cn/article/pohppp.html

其他資訊

在線咨詢
服務熱線
服務熱線:028-86922220
TOP
主站蜘蛛池模板: 欧美精品毛片 | 忘忧草在线影院www日本 | 一本大道久久香蕉成人网 | 性色av免费观看 | 91精品激情在线观看最新更新 | 激情文学小说区另类小说 | 成人av网址在线 | 浪潮av色综合久久天堂 | 老司机深夜福利在线观看 | 亚洲精品网站免费 | 91福利影院在线观看 | 日本69xxxxxxxx| 欧美日韩国产超高清免费看片 | 四虎影视8848h| 午夜成人爽爽爽视频在线观看 | 日韩一二三区视频 | 色呦呦视频在线 | 91在线91拍拍在线91 | 999免费观看视频 | 中文字幕在线观看国产推理片 | 91久久国产综合久久91 | 久久久久久免费精品一区二区三区 | 好爽啊中文字幕一区二区久久 | 131MM少妇做爰视频 | 深夜av福利 | 天天狠天天天天透在线 | 黄色毛片在线播放 | 国产精品推荐制服丝袜 | 麻豆蜜桃九色在线视频 | 日本xxx在线播放 | 午夜视频在线观看免费视频 | 国产毛片毛片毛片 | 久久久国产精品亚洲一区 | VIDEOS日本熟妇人妻多毛 | 国产成人欧美一区二区三区一色天 | 特黄特色高清不卡免费视频 | 十八女毛片 | 男女啪啪抽搐呻吟高潮动态图 | 亚洲成A人V欧美综合天堂麻豆 | 国产免费特黄淫乱片 | 久久久久成人精品亚洲国产 |