java線程池核心線程不被摧毀的原理及分析
更新時間:2025年05月07日 11:18:04 作者:春風十里不及你
這篇文章主要介紹了java線程池核心線程不被摧毀的原理及分析,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
為什么要用線程池?
- 減少了創(chuàng)建和銷毀線程的次數,每個工作線程都可以被重復利用
- 可以根據系統(tǒng)的承受能力,調整線程池中工作線線程的數目,防止因線程過多消耗內存,也避免了因線程過少,浪費系統(tǒng)資源
如何做到每個工作線程都可以被重復利用呢?
先看下線程池的工作原理:

原理如上圖,線程池有七個核心參數
corePoolSize線程池核心線程數maximumPoolSize線程池最大線程數量keepAliveTime空閑線程存活時間unit空閑線程存活時間單位workQueue工作隊列threadFactory線程工廠handler拒絕策略
線程池之所以能做到重復利用,是因為線程池的核心線程不會被摧毀,執(zhí)行完任務后會重復利用
線程池是如何保持核心線程不被摧毀呢?
首先看先線程池是如何處理任務的,如下圖

下面我們看下核心部分源碼:
- 當有一個任務添加進來時,線程池會創(chuàng)建一個Worker,Worker是實現Runnable方法的,所以Worker執(zhí)行時會調用run方法,run方法會接著調用runWoker方法
- 主要看這一行代碼,調用getTask方法獲取任務并且執(zhí)行 while (task != null || (task = getTask()) != null)
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
// 主要看這一行代碼,調用getTask方法獲取任務并且執(zhí)行
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);
Throwable thrown = null;
try {
task.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 {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}- 看下getTask方法是如何實現的
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf(c);
// Are workers subject to culling?
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}- 主要看這幾行代碼

- getTask方法通過調用任務隊列的take方法,不斷的獲取線程

- 如果任務隊列里面數量為0,則會一直阻塞,一直等到有任務加入,從而保證了核心線程不被摧毀
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
UniApp?+?SpringBoot?實現支付寶支付和退款功能
這篇文章主要介紹了UniApp?+?SpringBoot?實現支付寶支付和退款功能,基本的?SpringBoot?的腳手架,可以去IDEA?自帶的快速生成腳手架插件,本文通過實例代碼給大家介紹的非常詳細,需要的朋友參考下吧2022-06-06
mac下idea啟動web項目報錯java.net.SocketException:socket closed
本文主要介紹了作者在項目啟動時遇到的一個問題——無法打開調試端口,經過一系列排查和嘗試,最終發(fā)現是由于權限問題導致的,作者還分享了如何修改文件權限的方法,并提醒大家不要隨意kill掉占用端口的進程2024-12-12
springboot jdbctemplate如何實現多數據源
這篇文章主要介紹了springboot jdbctemplate如何實現多數據源問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07

