我們繼續討論ThreadPoolExecutor線程池。上篇文章給出的最簡單的ThreadPoolExecutor線程池的使用方式中,我們只採用了ThreadPoolExecutor最簡單的一個建構函式:
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)
實際上ThreadPoolExecutor線程池有很多種建構函式,其中最複雜的一種建構函式是:
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
在上文中我們還沒有介紹的workQueue、threadFactory和handler參數,將是本文講解的重點。 一:ThreadFactory的使用
線程池最主要的一項工作,就是在滿足某些條件的情況下建立線程。而在ThreadPoolExecutor線程池中,建立線程的工作交給ThreadFactory來完成。要使用線程池,就必須要指定ThreadFactory。
類似於上文中,如果我們使用的建構函式時並沒有指定使用的ThreadFactory,這個時候ThreadPoolExecutor會使用一個預設的ThreadFactory:DefaultThreadFactory。(這個類在Executors工具類中)
當然,在某些特殊業務情境下,還可以使用一個自訂的ThreadFactory線程工廠,如下程式碼片段:
import java.util.concurrent.ThreadFactory;/** * 測試自訂的一個線程工廠 */public class TestThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { return new Thread(r); }}二:線程池的等待隊列
在使用ThreadPoolExecutor線程池的時候,需要指定一個實現了BlockingQueue介面的任務等待隊列。在ThreadPoolExecutor線程池的API文檔中,一共推薦了三種等待隊列,它們是:SynchronousQueue、LinkedBlockingQueue和ArrayBlockingQueue; 隊列和棧
● 隊列:是一種特殊的線性結構,允許線上性結構的前端進行刪除/讀取操作;允許線上性結構的後端進行插入操作;這種線性結構具有“先進先出”的操作特點:
但是在實際應用中,隊列中的元素有可能不是以“進入的順序”為排序依據的。例如我們將要講到的PriorityBlockingQueue隊列。
● 棧:棧也是一種線性結構,但是棧和隊列相比只允許線上性結構的一端進行操作,入棧和出棧都是在一端完成。
2.1有限隊列
● SynchronousQueue:
“是這樣 一種阻塞隊列,其中每個 put 必須等待一個 take,反之亦然。同步隊列沒有任何內部容量。翻譯一下:這是一個內部沒有任何容量的阻塞隊列,任何一次插入操作的元素都要等待相對的刪除/讀取操作,否則進行插入操作的線程就要一直等待,反之亦然。
SynchronousQueue<Object> queue = new SynchronousQueue<Object>();// 不要使用add,因為這個隊列內部沒有任何容量,所以會拋出異常“IllegalStateException”// queue.add(new Object());// 操作線程會在這裡被阻塞,直到有其他動作線程取走這個對象queue.put(new Object());
● ArrayBlockingQueue:
一個由數組支援的有界阻塞隊列。此隊列按 FIFO(先進先出)原則對元素進行排序。新元素插入到隊列的尾部,隊列擷取操作則是從隊列頭部開始獲得元素。這是一個典型的“有界緩衝區”,固定大小的數組在其中保持生產者插入的元素和使用者提取的元素。一旦建立了這樣的緩衝區,就不能再增加其容量。試圖向已滿隊列中放入元素會導致操作受阻塞;試圖從空隊列中提取元素將導致類似阻塞。
// 我們建立了一個ArrayBlockingQueue,並且設定隊列空間為2ArrayBlockingQueue<Object> arrayQueue = new ArrayBlockingQueue<Object>(2);// 插入第一個對象arrayQueue.put(new Object());// 插入第二個對象arrayQueue.put(new Object());// 插入第三個對象時,這個操作線程就會被阻塞。arrayQueue.put(new Object());// 請不要使用add操作,和SynchronousQueue的add操作一樣,它們都使用了AbstractQueue中的add實現
2.2無限隊列
● LinkedBlockingQueue:
LinkedBlockingQueue是我們在ThreadPoolExecutor線程池中常用的等待隊列。它可以指定容量也可以不指定容量。由於它具有“無限容量”的特性,所以我還是將它歸入了無限隊列的範疇(實際上任何無限容量的隊列/棧都是有容量的,這個容量就是Integer.MAX_VALUE)。
LinkedBlockingQueue的實現是基於鏈表結構,而不是類似ArrayBlockingQueue那樣的數組。但實際使用過程中,不需要關心它的內部實現,如果指定了LinkedBlockingQueue的容量大小,那麼它反映出來的使用特性就和ArrayBlockingQueue類似了。
LinkedBlockingQueue<Object> linkedQueue = new LinkedBlockingQueue<Object>(2);linkedQueue.put(new Object());// 插入第二個對象linkedQueue.put(new Object());// 插入第三個對象時,這個操作線程就會被阻塞。linkedQueue.put(new Object());
=======================================
// 或者如下使用:LinkedBlockingQueue<Object> linkedQueue = new LinkedBlockingQueue<Object>();linkedQueue.put(new Object());// 插入第二個對象linkedQueue.put(new Object());// 插入第N個對象時,都不會阻塞linkedQueue.put(new Object());
● LinkedBlockingDeque
LinkedBlockingDeque是一個基於鏈表的雙端隊列。LinkedBlockingQueue的內部結構決定了它只能從隊列尾部插入,從隊列頭部取出元素;但是LinkedBlockingDeque既可以從尾部插入/取出元素,還可以從頭部插入元素/取出元素。
LinkedBlockingDeque<TempObject> linkedDeque = new LinkedBlockingDeque<TempObject>();// push ,可以從隊列的頭部插入元素linkedDeque.push(new TempObject(1));linkedDeque.push(new TempObject(2));linkedDeque.push(new TempObject(3));// poll , 可以從隊列的頭部取出元素TempObject tempObject = linkedDeque.poll();// 這裡會列印 tempObject.index = 3System.out.println("tempObject.index = " + tempObject.getIndex());// put , 可以從隊列的尾部插入元素linkedDeque.put(new TempObject(4));linkedDeque.put(new TempObject(5));// pollLast , 可以從隊列尾部取出元素tempObject = linkedDeque.pollLast();// 這裡會列印 tempObject.index = 5System.out.println("tempObject.index = " + tempObject.getIndex());
● PriorityBlockingQueue
PriorityBlockingQueue是一個按照優先順序進行內部元素排序的無限隊列。存放在PriorityBlockingQueue中的元素必須實現Comparable介面,這樣才能通過實現compareTo()方法進行排序。優先順序最高的元素將始終排在隊列的頭部;PriorityBlockingQueue不會保證優先順序一樣的元素的排序,也不保證當前隊列中除了優先順序最高的元素以外的元素,隨時處於正確排序的位置。
這是什麼意思呢。PriorityBlockingQueue並不保證除了隊列頭部以外的元素排序一定是正確的。請看下面的範例程式碼:
PriorityBlockingQueue<TempObject> priorityQueue = new PriorityBlockingQueue<TempObject>();priorityQueue.put(new TempObject(-5));priorityQueue.put(new TempObject(5));priorityQueue.put(new TempObject(-1));priorityQueue.put(new TempObject(1));// 第一個元素是5// 實際上在還沒有執行priorityQueue.poll()語句的時候,隊列中的第二個元素不一定是1TempObject targetTempObject = priorityQueue.poll();System.out.println("tempObject.index = " + targetTempObject.getIndex());// 第二個元素是1targetTempObject = priorityQueue.poll();System.out.println("tempObject.index = " + targetTempObject.getIndex());// 第三個元素是-1targetTempObject = priorityQueue.poll();System.out.println("tempObject.index = " + targetTempObject.getIndex());// 第四個元素是-5targetTempObject = priorityQueue.poll();System.out.println("tempObject.index = " + targetTempObject.getIndex());
// 這個元素類,必須實現Comparable介面private static class TempObject implements Comparable<TempObject> { private int index; public TempObject(int index) { this.index = index; } /** * @return the index */ public int getIndex() { return index; } /* (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(TempObject o) { return o.getIndex() - this.index; }}
● LinkedTransferQueue
LinkedTransferQueue也是一個無限隊列,它除了具有一般隊列的操作特性外(先進先出),還具有一個阻塞特性:LinkedTransferQueue可以由一對生產者/消費者線程進行操作,當消費者將一個新的元素插入隊列後,消費者線程將會一直等待,直到某一個消費者線程將這個元素取走,反之亦然。
LinkedTransferQueue的操作特性可以由下面這段代碼提現。在下面的程式碼片段中,有兩中類型的線程:生產者和消費者,這兩類線程互相等待對方的操作:
/** * 生產者線程 */private static class ProducerRunnable implements Runnable { private LinkedTransferQueue<TempObject> linkedQueue; public ProducerRunnable(LinkedTransferQueue<TempObject> linkedQueue) { this.linkedQueue = linkedQueue; } @Override public void run() { for(int index = 1 ; ; index++) { try { // 向LinkedTransferQueue隊列插入一個新的元素 // 然後生產者線程就會等待,直到有一個消費者將這個元素從隊列中取走 this.linkedQueue.transfer(new TempObject(index)); } catch (InterruptedException e) { e.printStackTrace(System.out); } } }}/** * 消費者線程 */private static class ConsumerRunnable implements Runnable { private LinkedTransferQueue<TempObject> linkedQueue; public ConsumerRunnable(LinkedTransferQueue<TempObject> linkedQueue) { this.linkedQueue = linkedQueue; } @Override public void run() { Thread currentThread = Thread.currentThread(); while(!currentThread.isInterrupted()) { try { // 等待,直到從LinkedTransferQueue隊列中得到一個元素 TempObject targetObject = this.linkedQueue.take(); System.out.println("線程(" + currentThread.getId() + ")取得targetObject.index = " + targetObject.getIndex()); } catch (InterruptedException e) { e.printStackTrace(System.out); } } }}
=====以下是啟動代碼:
LinkedTransferQueue<TempObject> linkedQueue = new LinkedTransferQueue<TempObject>();// 這是一個生產者線程Thread producerThread = new Thread(new ProducerRunnable(linkedQueue));// 這裡有兩個消費者線程Thread consumerRunnable1 = new Thread(new ConsumerRunnable(linkedQueue));Thread consumerRunnable2 = new Thread(new ConsumerRunnable(linkedQueue));// 開始運行producerThread.start();consumerRunnable1.start();consumerRunnable2.start();// 這裡只是為了main不退出,沒有任何示範含義Thread currentThread = Thread.currentThread();synchronized (currentThread) { currentThread.wait();}三:拒絕任務(handler)
在ThreadPoolExecutor線程池中還有一個重要的介面:RejectedExecutionHandler。當提交給線程池的某一個新任務無法直接被線程池中“核心線程”直接處理,又無法加入等待隊列,也無法建立新的線程執行;又或者線程池已經調用shutdown()方法停止了工作;又或者線程池不是處於正常的工作狀態;這時候ThreadPoolExecutor線程池會拒絕處理這個任務,觸發建立ThreadPoolExecutor線程池時定義的RejectedExecutionHandler介面的實現
在建立ThreadPoolExecutor線程池時,一定會指定RejectedExecutionHandler介面的實現。如果調用的是不需要指定RejectedExecutionHandler介面的建構函式,如:
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory)
那麼ThreadPoolExecutor線程池在建立時,會使用一個預設的RejectedExecutionHandler介面實現,原始碼片段如下:
public class ThreadPoolExecutor extends AbstractExecutorService { ...... /** * The default rejected execution handler */ private static final RejectedExecutionHandler defaultHandler = new AbortPolicy(); ...... // 可以看到,ThreadPoolExecutor中的兩個沒有指定RejectedExecutionHandler // 介面的建構函式,都是使用了一個RejectedExecutionHandler介面的預設實現:AbortPolicy public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); } ...... public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, defaultHandler); } ......}
實際上,在ThreadPoolExecutor中已經提供了四種可以直接使用的RejectedExecutionHandler介面的實現:
● CallerRunsPolicy:
這個拒絕處理器,將直接運行這個任務的run方法。但是,請注意並不是在ThreadPoolExecutor線程池中的線程中運行,而是直接調用這個任務實現的run方法。原始碼如下:
public static class CallerRunsPolicy implements RejectedExecutionHandler { /** * Creates a {@code CallerRunsPolicy}. */ public CallerRunsPolicy() { } /** * Executes task r in the caller's thread, unless the executor * has been shut down, in which case the task is discarded. * * @param r the runnable task requested to be executed * @param e the executor attempting to execute this task */ public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { if (!e.isShutdown()) { r.run(); } }}
● AbortPolicy:
這個處理器,在任務被拒絕後會建立一個RejectedExecutionException異常並拋出。這個處理過程也是ThreadPoolExecutor線程池預設的RejectedExecutionHandler實現。
● DiscardPolicy:
DiscardPolicy處理器,將會默默丟棄這個被拒絕的任務,不會拋出異常,也不會通過其他方式執行這個任務的任何一個方法,更不會出現任何的日誌提示。
● DiscardOldestPolicy:
這個處理器很有意思。它會檢查當前ThreadPoolExecutor線程池的等待隊列。並調用隊列的poll()方法,將當前處於等待隊列列頭的等待任務強行取出,然後再試圖將當前被拒絕的任務提交到線程池執行:
public static class DiscardOldestPolicy implements RejectedExecutionHandler { ...... public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { if (!e.isShutdown()) { e.getQueue().poll(); e.execute(r); } } ......}
實際上查閱這四種ThreadPoolExecutor線程池內建的拒絕處理器實現,您可以發現CallerRunsPolicy、DiscardPolicy、DiscardOldestPolicy處理器針對被拒絕的任務並不是一個很好的處理方式。
CallerRunsPolicy在非線程池以外直接調用任務的run方法,可能會造成安全執行緒上的問題;DiscardPolicy默默的忽略掉被拒絕任務,也沒有輸出日誌或者提示,開發人員不會知道線程池的處理過程出現了錯誤;DiscardOldestPolicy中e.getQueue().poll()的方式好像是科學的,但是如果等待隊列出現了容量問題,大多數情況下就是這個線程池的代碼出現了BUG。最科學的的還是AbortPolicy提供的處理方式:拋出異常,由開發人員進行處理。