轉載自:https://www.jianshu.com/p/f030aa5d7a28java
ThreadPoolExecutor提供了四個構造方法:dom
咱們以最後一個構造方法(參數最多的那個),對其參數進行解釋:ide
public ThreadPoolExecutor(int corePoolSize, // 1 int maximumPoolSize, // 2 long keepAliveTime, // 3 TimeUnit unit, // 4 BlockingQueue<Runnable> workQueue, // 5 ThreadFactory threadFactory, // 6 RejectedExecutionHandler handler ) { //7 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; }
序號 | 名稱 | 類型 | 含義 |
---|---|---|---|
1 | corePoolSize | int | 核心線程池大小 |
2 | maximumPoolSize | int | 最大線程池大小 |
3 | keepAliveTime | long | 線程最大空閒時間 |
4 | unit | TimeUnit | 時間單位 |
5 | workQueue | BlockingQueue<Runnable> | 線程等待隊列 |
6 | threadFactory | ThreadFactory | 線程建立工廠 |
7 | handler | RejectedExecutionHandler | 拒絕策略 |
若是對這些參數做用有疑惑的請看 ThreadPoolExecutor概述。
知道了各個參數的做用後,咱們開始構造符合咱們期待的線程池。首先看JDK給咱們預約義的幾種線程池:this
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
- corePoolSize與maximumPoolSize相等,即其線程全爲核心線程,是一個固定大小的線程池,是其優點;
- keepAliveTime = 0 該參數默認對核心線程無效,而FixedThreadPool所有爲核心線程;
- workQueue 爲LinkedBlockingQueue(無界阻塞隊列),隊列最大值爲Integer.MAX_VALUE。若是任務提交速度持續大餘任務處理速度,會形成隊列大量阻塞。由於隊列很大,頗有可能在拒絕策略前,內存溢出。是其劣勢;
- FixedThreadPool的任務執行是無序的;
適用場景:可用於Web服務瞬時削峯,但需注意長時間持續高峯狀況形成的隊列阻塞。spa
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
- corePoolSize = 0,maximumPoolSize = Integer.MAX_VALUE,即線程數量幾乎無限制;
- keepAliveTime = 60s,線程空閒60s後自動結束。
- workQueue 爲 SynchronousQueue 同步隊列,這個隊列相似於一個接力棒,入隊出隊必須同時傳遞,由於CachedThreadPool線程建立無限制,不會有隊列等待,因此使用SynchronousQueue;
適用場景:快速處理大量耗時較短的任務,如Netty的NIO接受請求時,可以使用CachedThreadPool。線程
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
咋一瞅,不就是newFixedThreadPool(1)嗎?定眼一看,這裏多了一層FinalizableDelegatedExecutorService包裝,這一層有什麼用呢,寫個dome來解釋一下:3d
public static void main(String[] args) { ExecutorService fixedExecutorService = Executors.newFixedThreadPool(1); ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) fixedExecutorService; System.out.println(threadPoolExecutor.getMaximumPoolSize()); threadPoolExecutor.setCorePoolSize(8); ExecutorService singleExecutorService = Executors.newSingleThreadExecutor(); // 運行時異常 java.lang.ClassCastException // ThreadPoolExecutor threadPoolExecutor2 = (ThreadPoolExecutor) singleExecutorService; }
對比能夠看出,FixedThreadPool能夠向下轉型爲ThreadPoolExecutor,並對其線程池進行配置,而SingleThreadExecutor被包裝後,沒法成功向下轉型。所以,SingleThreadExecutor被定之後,沒法修改,作到了真正的Single。rest
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); }
newScheduledThreadPool調用的是ScheduledThreadPoolExecutor的構造方法,而ScheduledThreadPoolExecutor繼承了ThreadPoolExecutor,構造是仍是調用了其父類的構造方法。日誌
public ScheduledThreadPoolExecutor(int corePoolSize) { super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue()); }
對於ScheduledThreadPool本文不作描述,其特性請關注後續篇章。code
如下是自定義線程池,使用了有界隊列,自定義ThreadFactory和拒絕策略的demo:
public class ThreadTest { public static void main(String[] args) throws InterruptedException, IOException { int corePoolSize = 2; int maximumPoolSize = 4; long keepAliveTime = 10; TimeUnit unit = TimeUnit.SECONDS; BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(2); ThreadFactory threadFactory = new NameTreadFactory(); RejectedExecutionHandler handler = new MyIgnorePolicy(); ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); executor.prestartAllCoreThreads(); // 預啓動全部核心線程 for (int i = 1; i <= 10; i++) { MyTask task = new MyTask(String.valueOf(i)); executor.execute(task); } System.in.read(); //阻塞主線程 } static class NameTreadFactory implements ThreadFactory { private final AtomicInteger mThreadNum = new AtomicInteger(1); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r, "my-thread-" + mThreadNum.getAndIncrement()); System.out.println(t.getName() + " has been created"); return t; } } public static class MyIgnorePolicy implements RejectedExecutionHandler { public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { doLog(r, e); } private void doLog(Runnable r, ThreadPoolExecutor e) { // 可作日誌記錄等 System.err.println( r.toString() + " rejected"); // System.out.println("completedTaskCount: " + e.getCompletedTaskCount()); } } static class MyTask implements Runnable { private String name; public MyTask(String name) { this.name = name; } @Override public void run() { try { System.out.println(this.toString() + " is running!"); Thread.sleep(3000); //讓任務執行慢點 } catch (InterruptedException e) { e.printStackTrace(); } } public String getName() { return name; } @Override public String toString() { return "MyTask [name=" + name + "]"; } } }
輸出結果以下:
其中線程線程1-4先佔滿了核心線程和最大線程數量,而後四、5線程進入等待隊列,7-10線程被直接忽略拒絕執行,等1-4線程中有線程執行完後通知四、5線程繼續執行。