ThreadPoolExecutor提供了四個構(gòu)造方法:
我們以最后一個構(gòu)造方法(參數(shù)最多的那個)晰骑,對其參數(shù)進(jìn)行解釋:
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 | 線程創(chuàng)建工廠 |
7 | handler | RejectedExecutionHandler | 拒絕策略 |
如果對這些參數(shù)作用有疑惑的請看 ThreadPoolExecutor概述。
知道了各個參數(shù)的作用后乞娄,我們開始構(gòu)造符合我們期待的線程池惧互。首先看JDK給我們預(yù)定義的幾種線程池:
一鳍刷、預(yù)定義線程池
- FixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
- corePoolSize與maximumPoolSize相等鱼的,即其線程全為核心線程理盆,是一個固定大小的線程池,是其優(yōu)勢凑阶;
- keepAliveTime = 0 該參數(shù)默認(rèn)對核心線程無效猿规,而FixedThreadPool全部為核心線程;
- workQueue 為LinkedBlockingQueue(無界阻塞隊列)宙橱,隊列最大值為Integer.MAX_VALUE姨俩。如果任務(wù)提交速度持續(xù)大余任務(wù)處理速度,會造成隊列大量阻塞师郑。因為隊列很大环葵,很有可能在拒絕策略前,內(nèi)存溢出呕乎。是其劣勢积担;
- FixedThreadPool的任務(wù)執(zhí)行是無序的陨晶;
適用場景:可用于Web服務(wù)瞬時削峰猬仁,但需注意長時間持續(xù)高峰情況造成的隊列阻塞。
- CachedThreadPool
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
- corePoolSize = 0先誉,maximumPoolSize = Integer.MAX_VALUE湿刽,即線程數(shù)量幾乎無限制;
- keepAliveTime = 60s褐耳,線程空閑60s后自動結(jié)束诈闺。
- workQueue 為 SynchronousQueue 同步隊列,這個隊列類似于一個接力棒铃芦,入隊出隊必須同時傳遞雅镊,因為CachedThreadPool線程創(chuàng)建無限制,不會有隊列等待刃滓,所以使用SynchronousQueue仁烹;
適用場景:快速處理大量耗時較短的任務(wù),如Netty的NIO接受請求時咧虎,可使用CachedThreadPool卓缰。
- SingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
咋一瞅,不就是newFixedThreadPool(1)嗎?定眼一看征唬,這里多了一層FinalizableDelegatedExecutorService包裝捌显,這一層有什么用呢,寫個dome來解釋一下:
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();
// 運(yùn)行時異常 java.lang.ClassCastException
// ThreadPoolExecutor threadPoolExecutor2 = (ThreadPoolExecutor) singleExecutorService;
}
對比可以看出总寒,F(xiàn)ixedThreadPool可以向下轉(zhuǎn)型為ThreadPoolExecutor扶歪,并對其線程池進(jìn)行配置,而SingleThreadExecutor被包裝后摄闸,無法成功向下轉(zhuǎn)型击罪。因此,SingleThreadExecutor被定以后贪薪,無法修改媳禁,做到了真正的Single。
- ScheduledThreadPool
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
newScheduledThreadPool調(diào)用的是ScheduledThreadPoolExecutor的構(gòu)造方法画切,而ScheduledThreadPoolExecutor繼承了ThreadPoolExecutor竣稽,構(gòu)造是還是調(diào)用了其父類的構(gòu)造方法。
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
對于ScheduledThreadPool本文不做描述霍弹,其特性請關(guān)注后續(xù)篇章毫别。
二、自定義線程池
以下是自定義線程池典格,使用了有界隊列岛宦,自定義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(); // 預(yù)啟動所有核心線程
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); //讓任務(wù)執(zhí)行慢點(diǎn)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public String getName() {
return name;
}
@Override
public String toString() {
return "MyTask [name=" + name + "]";
}
}
}
輸出結(jié)果如下:
其中線程線程1-4先占滿了核心線程和最大線程數(shù)量,然后4耍缴、5線程進(jìn)入等待隊列砾肺,7-10線程被直接忽略拒絕執(zhí)行,等1-4線程中有線程執(zhí)行完后通知4防嗡、5線程繼續(xù)執(zhí)行变汪。
總結(jié),通過自定義線程池蚁趁,我們可以更好的讓線程池為我們所用裙盾,更加適應(yīng)我的實際場景。
多線程系列目錄(不斷更新中):
線程啟動原理
線程中斷機(jī)制
多線程實現(xiàn)方式
FutureTask實現(xiàn)原理
線程池之ThreadPoolExecutor概述
線程池之ThreadPoolExecutor使用
線程池之ThreadPoolExecutor狀態(tài)控制
線程池之ThreadPoolExecutor執(zhí)行原理
線程池之ScheduledThreadPoolExecutor概述
線程池的優(yōu)雅關(guān)閉實踐