java併發程式設計—— 執行緒池原理 詳解 ThreadPoolExecutor
為什麼要使用執行緒池
- 降低資源消耗: 通過重複利用執行緒,減少執行緒的建立銷燬損耗的資源
- 提高響應速度: 任務到達時,不用重新建立執行緒,之間可以使用已經建立好的執行緒執行
- 提高執行緒的可管理性
執行緒池實現分析
我們使用如下的demo來一步一步分析執行緒池
public class TheadPoolTest {
public static void main(String[] args) throws InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(2 );
// ExecutorService service = Executors.newCachedThreadPool();
// ExecutorService service = Executors.newWorkStealingPool();
for (int i = 0; i < 4; i++) {
service.submit(getTask());
//如果都是不需要返回結果的Runnable可以直接使用
//service.execute(getTask());
}
}
private static Runnable getTask() {
return new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getId());
}
};
}
}
1.初始化構造執行緒池
Executors是一個工廠類,裡面封裝了多個用於創造特定場景下使用的執行緒池的工廠方法。比如我們示例中的Executors.newFixedThreadPool(2)會返回一個固定執行緒個數的執行緒池。詳細來看看
//Executors:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
//ThreadPoolExecutor:
private static final RejectedExecutionHandler defaultHandler =
new AbortPolicy();
private static final RuntimePermission shutdownPerm =
new RuntimePermission("modifyThread");
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,
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;
}
ThreadPoolExecutor是真正構造執行緒池的類。其中的引數解釋如下:
- int corePoolSize
核心執行緒數,執行緒池中會長期保留的執行緒,即使執行緒池中有多個空閒執行緒,但是執行緒總數沒有達到corePoolSize,新任務提交後也會再次建立一個新的執行緒去處理任務。
超過這個corePoolsize數量的執行緒會在一段時間的空閒後被清理掉。
int maximumPoolSize
執行緒池中同時執行的執行緒最大的總數量long keepAliveTime
超過coerPoolSize的執行緒處於idle狀態時,允許存活的最大時間。這樣能減少大量空閒執行緒對資源的消耗。TimeUnit unit keepAliveTime的時間單位
BlockingQueue workQueue 阻塞佇列,用來存放提交過來的Runable任務
幾種常見的策略- Direct handoffs(傳遞手):
直接傳遞給執行緒執行(SynchronousQueue),它不會儲存任務,而是直接交給執行緒執行。如果沒有可用執行緒
那麼會建立一個新執行緒去執行,執行完了銷燬。這種執行緒池不會設定最大執行緒數以免任務丟棄。 Unbounded queues(無界佇列):
使用一個無界的佇列來存放任務(比如, 使用new LinkedBlockingQueue(),預設容量是Integer.Integer.MAX_VALUE),當新的任務被提交,執行緒數已經達到了coreSize,
這是不會再產生任何新的執行緒,任務都會入隊,直到coreThreads有可用的。
這種時候任務之間相互獨立的場景,如web頁面請求任務。Bounded queues(有界佇列):
一個有界佇列(ArrayBlockingQueue)通過合理設定maxnumPoolSize以防止資源被過度消耗,這種對任務的管理方式
更難於調控。佇列的size與執行緒池maxSize之間需要相互協調妥協:大佇列和小執行緒池可以減少CPU\OS資源\上線問切換的消耗。
但是會導致較低的吞吐量。 如果任務頻繁的阻塞(比如密集的IO,IO成為瓶頸),CPU也許導致大量空閒資源。
然而小佇列大執行緒池,CPU可以充分利用,但是頻繁的執行緒排程上下文切換同樣會導致吞吐量下降。
- Direct handoffs(傳遞手):
ThreadFactory threadFactory 用來建立執行緒池中執行緒的工廠類,可以設定daemon狀態、執行緒名稱、執行緒組以及優先順序等資訊
RejectedExecutionHandler handler
ThreadPoolExecutor.AbortPolicy(預設,拒絕策略)
當執行緒池沒有空餘執行緒、並且佇列已經滿了。這時候會預設採取拒絕策略,
丟棄任務並丟擲RejectedExecutionExceptionThreadPoolExecutor.CallerRunsPolicy
CallerRunsPolicy會使用當前提交任務的執行緒去執行任務,這種策略會導致任務提交的速度下降。ThreadPoolExecutor.DiscardPolicy
DiscardPolicy簡單來說就是直接丟棄任務,沒有任何反饋。
2.提交任務並執行
/**
*mainLock用來同步 woker set的訪問 和 相關的記錄
*/
private final ReentrantLock mainLock = new ReentrantLock();
/**
* Set containing all worker threads in pool. Accessed only when holding
* mainLock.
* 看到了,執行緒的這個池子就是用ReentrantLock維護的HashSet
*/
private final HashSet<Worker> workers = new HashSet<Worker>();
//(Executors父類) AbstractExecutorService
public Future<?> submit(Runnable task) {
if (task == null) throw new NullPointerException();
RunnableFuture<Void> ftask = newTaskFor(task, null);
execute(ftask);
return ftask;
}
//將Runnable task包裝為一個 FutureTask型別
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
return new FutureTask<T>(runnable, value);
}
/**FutureTask:
*
* 實現了Runnable介面、Future介面
* 一個可 取消的 非同步的計算任務。
* 這個類實現了Future基本功能:啟動、取消一個計算任務;
* 檢視這個計算任務是否執行完畢;
* 檢視計算結果(在計算完畢之後)。
* get()獲取執行的計算結果,如果計算沒有執行完畢,那麼會產生park阻塞。
*
* FutureTask可以用來包裝 Callable或者Runnable物件。
**/
//ThreadPoolExecutor.execute(Runnable command)
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
// 獲取ctl的大小.ctl中包裝了workerCount、runState兩個變數
int c = ctl.get();
// Step1
// 如果池中的執行緒數少於corePoolSize,嘗試建立一個新的執行緒去執行這個command.
if (workerCountOf(c) < corePoolSize) {// 通過位運算獲取workerCount。如果workerCount<coreSize
if (addWorker(command, true))// 創新新的執行緒執行command任務。
return;
c = ctl.get();
}
// Step2
// 如果這個任務可以成功入隊,再次對執行緒池執行狀態檢查:這裡使用了一個無界佇列(實際上是Integer.Max)
if (isRunning(c) && workQueue.offer(command)) {// 任務入隊
int recheck = ctl.get();
// 如果執行緒池已經處於非執行狀態,
// 那麼移除並使用handler處理這個任務
if (!isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
// Step3
// 如果入隊失敗,那麼我們嘗試新增一個執行緒。
// 如果新增失敗,那麼應該是執行緒池關閉了或者已經飽和了。那麼我們最終拒絕這個任務。
else if (!addWorker(command, false))
reject(command);
}
//ThreadPoolExecutor.addWorker(Runnable firstTask, boolean core)
private boolean addWorker(Runnable firstTask, boolean core) {
retry: for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
// 池處於非執行狀態 && ...
if (rs >= SHUTDOWN && !(rs == SHUTDOWN && firstTask == null && !workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);// 解包裝獲取workerCount
// workerCount>=CAPACITY || workerCount>=
if (wc >= CAPACITY || wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c))// CAS workerCount+1
break retry;// 退出最外層迴圈
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)
continue retry;
// else CAS failed due to workerCount change; retry inner loop
}
}
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
w = new Worker(firstTask);//將這個Task作為引數,初始化一個Woker
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// Recheck while holding lock.
// Back out on ThreadFactory failure or if
// shut down before lock acquired.
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);
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
t.start();//啟動woker執行緒
workerStarted = true;
}
}
} finally {
if (!workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
//ThreadPoolExecutor.Worker
//Woker是ThreadPoolExecutor的內部類,繼承了AQS(其中實現了一個簡單的排他鎖,不可重入)、實現了Runnable.
//Woker中建立了一個執行緒,處理完首個任務後會從佇列頭部獲取入隊的任務繼續執行
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
/** Delegates main run loop to outer runWorker */
public void run() {
runWorker(this);
}
//ThreadPoolExecutor
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
//預設state==-1,為-1的時候阻塞執行緒中斷。此次將-1設定為0,執行執行緒在執行期間響應中斷ts
w.unlock();
boolean completedAbruptly = true;
try {//迴圈從佇列頭部獲取任務並執行
while (task != null || (task = getTask()) != null) {
w.lock();
// 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 {
beforeExecute(wt, task);//hook befoer TaksExecute
Throwable thrown = null;
try {
task.run();//FutureTask.run—>Callable.run——>Runnable.run;執行結束後在FutureTaks中設定result.
} catch (RuntimeException x) {
thrown = x;
throw x;
} catch (Error x) {
thrown = x;
throw x;
} catch (Throwable x) {
thrown = x;
throw new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
執行緒池實現原理
java.util.concurrent.ThreadPoolExecutor.ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
Step1:如果執行緒池中執行緒數量沒有超過coreSize,則繼續建立新的執行緒(全域性鎖);否則執行Step2
全域性鎖
/**
* Lock held on updates to poolSize, corePoolSize,
* maximumPoolSize, runState, and workers set.
*/
private final ReentrantLock mainLock = new ReentrantLock();
Step2 : 如果執行緒池中執行緒數量超過coreSize,則把這個任務放入阻塞佇列中(BlockingQueue workQueue 尾部)
Step3 : 如果阻塞佇列滿了,則檢視是否達到執行緒池最大執行緒數,如果沒有繼續建立新執行緒(全域性鎖)執行這個任務;否則Step4 使用RejectedExecutionHandler拒絕策略處理任務。
Step4 : 使用拒絕策略處理任務:
AbortPolicy:直接丟擲RejectException異常
DiscardPolicy:直接丟棄這個任務
DiscardOldestPolicy:丟棄任務佇列中的頭部的任務,然後放入當前任務
CallerRunsPolicy: 直接用當前執行緒執行該任務
當執行緒池完成預熱後(threadSize>coreSize),每次任務進入都會執行Step2,放入阻塞佇列中,避免了獲取全域性鎖。
ThreadPoolExecutor.execute(Runnable command)原始碼:
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) {
if (runState == RUNNING && workQueue.offer(command)) {
if (runState != RUNNING || poolSize == 0)
ensureQueuedTaskHandled(command);
}
else if (!addIfUnderMaximumPoolSize(command))
reject(command); // is shutdown or saturated
}
}
ThreadPoolExecutor.addThread(Runnable firstTask)-新建立執行緒
private Thread addThread(Runnable firstTask) {
Worker w = new Worker(firstTask);
Thread t = threadFactory.newThread(w);
boolean workerStarted = false;
if (t != null) {
if (t.isAlive()) // precheck that t is startable
throw new IllegalThreadStateException();
w.thread = t;
workers.add(w);
int nt = ++poolSize;
if (nt > largestPoolSize)
largestPoolSize = nt;
try {
t.start();
workerStarted = true;
}
finally {
if (!workerStarted)
workers.remove(w);
}
}
return t;
}
執行緒池會把收到的Runnable任務封裝為封裝為Worker物件(implements Runnable),在這個woker裡執行,當這個收到的任務執行完,會繼續執行阻塞佇列裡的其他任務(從頭部獲取新任務).
execute()\submit() shutDown\shutDownNow
execute執行runnable任務,沒有返回值。submit會返回Future物件,future物件get()方法阻塞式獲取執行後返回的結果。
shutDown\shutDownNow都是遍歷所有執行緒,依次執行interrupt操作
Executors使用靜態工廠返回特定型別的執行緒池:
FixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}
keepAliveTime設定為0,表示超過coreThread數量的執行緒會立刻被終止。
FixedThreadPool使用了LinkedBlockingQueue()這個無界的阻塞佇列,表示達到了coreThread數量後,新進入的任務總是會放入任務佇列中,不會建立多餘的執行緒,執行緒數量不會超過coreThread數量。因此也不涉及到任何對任務的丟棄等處理策略。
它限定了執行緒的數量,適用於需要控制資源的使用,負載較重的機器。
CachedThreadPool
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
threadFactory);
}
CacheThreadPool對執行緒數量基本沒有限制(Integer.MAX_VALUE),它使用了SynchronousQueue作為執行緒池的任務佇列
具體執行情況:
- step1:主執行緒呼叫SynchronousQueue.offer(task)插入一個任務,如果當前有空閒執行緒可以執行Synchronous.poll,那麼這個空閒執行緒繼續執行這個任務
- step2:如果此時插入一個任務時,沒有空閒執行緒可以執行Synchronous.poll操作,此時建立一個會建立一個新的執行緒執行這個任務。
- step3:新建立執行緒執行完任務後,會繼續執行SynchronousQueue.poll()操作,如果60s內主執行緒沒有提交任務,則這個執行緒將終止
SynchronousQueue是個沒有容量的阻塞佇列,每個插入操作必須等待另一個執行緒的移除操作,反之亦然。移除與插入的兩個執行緒必須對應。
CacheThreadPool是個無限制的執行緒池,適用於 執行任務多,每個任務執行時間短或負載較輕的機器