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,则添加新的工作线程。
- 如果我们将任务添加到等待池中失败并且再次尝试添加工作线程失败,那么就直接拒绝掉这个任务。