Execute执行流程说明(分为三个步骤):
源代码中的注释:
- Proceed in 3 steps:
-
- 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.
//第一步:检查核心线程池。如果正在运行的核心线程数,那么从核心线程池中开启一个没有使用的线程用于执行任务。 在调用addWorker的时候会自动检查线程池状态和线程数,并且在遇到不该添加线程的情况报错。(不该添加线程:要么线程数量已经大于maximumPoolSize,要么线程池当前不在RUNNING状态)
-
- 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.
//当一个任务满足进入等待线程池分配线程的等待队列的时候,(即当前线程池的corePoolSize已经满了,但阻塞队列中还有空间可以分配)双重检查,首先检查线程池是否还处于运行状态以及等待线程池分配线程的阻塞队列中能否添加当前任务。接着第二次检查在执行ctl操作的时候线程池是否还处在运行状态,检查当前任务能否被删去。第二次判断如果有一个判断失败,调用拒绝策略。反之,如果两次判断均成功,那么在线程池中添加当前任务。
如果线程池中的线程数量为0,那么调用addWorker创建新的线程空间,如果没有完成任务线程的添加,那么说明当前任务的添加操作中有条件不满足,调用拒绝策略。 -
- 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.
如果我们不能让当前任务入等待队列,我们尝试在线程池中添加新线程(如果线程池的线程数量没有超过maximumPoolSize的话创建新线程),如果失败,调用拒绝策略。
拒绝策略:
1、拒绝对应任务的提交
2、拒绝任务提交不抛出异常
3、拒绝最老的任务提交
4、调用其他线程进行执行
execute方法执行逻辑:
——---------------—————————————————————–
补充addWorker的执行逻辑图: