1.线程池处理流程
当线程池提交一个新的任务时,线程池的处理流程如下:
- 线程池判断核心线程池corePoolSize是否已满(是否都在执行任务),未满则创建线程执行任务;已满则下一步
- 线程池判断工作队列BlockingQueue是否已满,未满则将任务放进队列;已满则下一步
- 线程池判断池中线程数是否达到maximumPoolSize(所有线程是否都已处在工作状态),如果没有则创建新的线程执行任务;如果已满则交给饱和策略RejectedExecutionHandler处理。
2.execute()方法
有了上面的线程池处理流程,我们来看看线程池ThreadPoolExecutor执行execute方法流程,如下图:
- 如果当前运行线程少于corePoolSize,则创建新县城来执行任务(这一步需要获取全局锁)
- 如果运行线程等于多于corePoolSize,则将任务加入BlockingQueue
- 如果BlockingQueue工作队列已满,则创建新的线程来处理任务(这一步需要获取全局锁)
- 如果线程池饱和(工作队列已满,线程池数达到maximumPoolSize),任务将被拒绝,并调用饱和策略RejectedExecutionHandler.rejectExecution()处理
下面结合上面的流程来瞅瞅大胡子 Doug Lea的源码
3.线程池源码
注释中3个steps也对应着上面的流程
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);
}
下一篇博客来详细讲一下线程池ThreadPoolExecutor