状态解释
ThreadPoolExecutor的成员变量ctl是用来控制状态和Worker数量,代码如下:
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
AtomicInteger使用Int作为存储,Int有32位,ThreadPoolExecutor对ctl的32位进行划分,其中高三位用于存储线程池状态,低29位用来存储Worker数量。
状态说明
# | 状态名 | 状态说明 | 状态值 |
---|---|---|---|
1 | RUNNING | 接受新任务并处理队列中的任务 | -536870912 |
2 | SHUTDOWN | 不接受新任务,但是会处理队列中的任务 | 0 |
3 | STOP | 不接受新任务,同时也不会处理队列中的任务,并且会中断正在执行的任务 | 536870912 |
4 | TIDYING | 所有的任务都已经终止,Woker线程数量为0并且会调用terminated()钩子函数 | 1073741824 |
5 | TERMINATED | terminated()钩子函数执行完成后 | 1610612736 |
状态值关系
线程池状态值的关系:TERMINATED > TIDYING > STOP > SHUTDOWN > RUNNING。
状态值关系在ThreadPoolExecutor中经常使用,所以知道状态值的大小关系能够更好的理解代码实现。
JDK中对状态的说明
The runState provides the main lifecycle control, taking on values:
- RUNNING: Accept new tasks and process queued tasks
- SHUTDOWN: Don’t accept new tasks, but process queued tasks
- STOP: Don’t accept new tasks, don’t process queued tasks,
-
and interrupt in-progress tasks
- TIDYING: All tasks have terminated, workerCount is zero,
-
the thread transitioning to state TIDYING
-
will run the terminated() hook method
- TERMINATED: terminated() has completed