在多線程編程中,線程池是一種非常重要的技術。它可以幫助我們有效地管理線程資源,避免頻繁地創建和銷毀線程,從而提高系統的性能和穩定性。Java提供了java.util.concurrent
包來支持線程池的實現,其中最核心的類是ThreadPoolExecutor
。本文將深入分析ThreadPoolExecutor
的實現原理,并通過源碼解析其工作流程。
線程池是一種多線程處理形式,它通過預先創建一定數量的線程,并將任務提交到線程池中執行,從而避免了頻繁創建和銷毀線程的開銷。線程池中的線程可以重復使用,執行完一個任務后,線程不會被銷毀,而是繼續執行下一個任務。
ThreadPoolExecutor
類ThreadPoolExecutor
是Java線程池的核心實現類,它提供了線程池的基本功能。ThreadPoolExecutor
繼承自AbstractExecutorService
,并實現了ExecutorService
接口。
ThreadPoolExecutor
使用一個AtomicInteger
類型的變量ctl
來表示線程池的狀態和線程數量。ctl
的高3位表示線程池的狀態,低29位表示線程池中的線程數量。
線程池的狀態包括:
ThreadPoolExecutor
的構造方法ThreadPoolExecutor
提供了多個構造方法,最常用的構造方法如下:
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;
}
該構造方法初始化了線程池的核心參數,包括核心線程數、最大線程數、空閑時間、任務隊列、線程工廠和拒絕策略。
execute
方法execute
方法是線程池的核心方法,用于提交任務到線程池中執行。其源碼如下:
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (!isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}
execute
方法的主要邏輯如下:
null
,如果是則拋出NullPointerException
。addWorker
方法addWorker
方法用于創建新線程并執行任務。其源碼如下:
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);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c))
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);
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();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
addWorker
方法的主要邏輯如下:
false
。false
。Worker
對象,并將其添加到workers
集合中。Worker
線程,如果啟動成功則返回true
,否則調用addWorkerFailed
方法進行清理。runWorker
方法runWorker
方法是Worker
線程的執行邏輯。其源碼如下:
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
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);
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);
}
}
runWorker
方法的主要邏輯如下:
null
,則執行任務。null
,則調用getTask
方法從任務隊列中獲取任務。beforeExecute
方法進行前置處理。afterExecute
方法進行后置處理。completedAbruptly
為true
。processWorkerExit
方法處理線程退出。getTask
方法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
方法的主要邏輯如下:
null
。poll
方法從任務隊列中獲取任務,如果超時則返回null
。take
方法從任務隊列中獲取任務,如果任務隊列為空則阻塞等待。processWorkerExit
方法processWorkerExit
方法用于處理線程退出。其源碼如下:
private void processWorkerExit(Worker w, boolean completedAbruptly) {
if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted
decrementWorkerCount();
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
completedTaskCount += w.completedTasks;
workers.remove(w);
} finally {
mainLock.unlock();
}
tryTerminate();
int c = ctl.get();
if (runStateLessThan(c, STOP)) {
if (!completedAbruptly) {
int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
if (min == 0 && ! workQueue.isEmpty())
min = 1;
if (workerCountOf(c) >= min)
return; // replacement not needed
}
addWorker(null, false);
}
}
processWorkerExit
方法的主要邏輯如下:
workers
集合中移除該線程。tryTerminate
方法嘗試終止線程池。ThreadPoolExecutor
提供了四種內置的拒絕策略:
RejectedExecutionException
異常。除了使用內置的拒絕策略外,我們還可以自定義拒絕策略。自定義拒絕策略需要實現RejectedExecutionHandler
接口,并重寫rejectedExecution
方法。
public class CustomRejectedExecutionHandler implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
// 自定義拒絕策略的邏輯
}
}
線程池的監控主要包括以下幾個方面:
isShutdown
、isTerminated
等方法監控線程池的狀態。getPoolSize
、getActiveCount
等方法監控線程池中的線程數量。getQueue
方法獲取任務隊列,并監控其大小。getCompletedTaskCount
方法獲取已完成任務的數量。線程池的調優主要包括以下幾個方面:
SynchronousQueue
;如果任務較少且執行時間較長,可以選擇LinkedBlockingQueue
。CallerRunsPolicy
;如果任務的重要性較低,可以選擇DiscardPolicy
。本文詳細分析了Java線程池的實現原理,并通過源碼解析了ThreadPoolExecutor
的工作流程。線程池是多線程編程中非常重要的技術,合理地使用線程池可以顯著提高系統的性能和穩定性。在實際開發中,我們應根據系統的負載情況和任務的特性,合理地設置線程池的參數,并進行監控和調優,以確保線程池的高效運行。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。