FixedThreadPoolExecutor的原理分析
定義FixedThreadPoolExecutor其實是利用ThreadPoolExecutor來實現的,因此我們只需要理解ThreadPoolExecutor這個類即可。
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
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(Runnable r)方法,有三個步驟:
- 如果當前工作線程小於corePoolSize,即小於我們定義的線程池的大小,那麼就直接增加Worker線程。如果添加成功,那麼直接就返回了。否則走向第二步
- 如果線程池正在工作並且成功添加到了等待池中,那麼我們重新檢查一下是否工作線程池的工作狀態,如果線程池停止工作並且刪除任務失敗,那麼直接拒絕掉這個任務(不明白爲什麼要加上這層判斷),如果工作線程數量爲0,則添加新的工作線程。
- 如果我們將任務添加到等待池中失敗並且再次嘗試添加工作線程失敗,那麼就直接拒絕掉這個任務。