RUNNING

能接收新任务并处理已添加的任务
线程池一旦创建,就处于RUNNING状态,此时线程池中的任务数为0

SHUTDOWN

不接收新任务,但能处理已添加的任务
调用线程池的shutdown()接口,线程池由 RUNNING 》 SHUTDOWN

STOP

线程池处于STOP状态,不接收新任务,不处理已添加的任务,并且会中断正在处理的任务
调用线程池的shutdownNow()接口,线程池由 RUNNING or SHUTDOWN 》 STOP

TIDYING

当所有任务已终止,ctl记录的任务数为0,线程池的状态会变为TIDYING
当线程池的状态变为TIDYING状态时,会调用钩子函数terminated(),该方法在ThreadPoolExecutor中是空的,若用户想在线程池变为TIDYING时进行相应的处理,就需要重载terminated()函数
当线程池状态为SHUTDOWN,阻塞队列为空,线程池中执行的任务也为空时,由 SHUTDOWN 》 TIDYING
当线程池状态为STOP,线程池中执行的任务为空时,由 STOP》 TIDYING

TERMINATED

线程池彻底终止
线程池处于TIDYING状态,调用terminated()时,由 TIDYING 》 TERMINATED

ThreadPoolExecutor 源码注释

 
 * 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
 *
 * The numerical order among these values matters, to allow
 * ordered comparisons. The runState monotonically increases over
 * time, but need not hit each state. The transitions are:
 *
 * RUNNING -> SHUTDOWN
 *    On invocation of shutdown(), perhaps implicitly in finalize()
 * (RUNNING or SHUTDOWN) -> STOP
 *    On invocation of shutdownNow()
 * SHUTDOWN -> TIDYING
 *    When both queue and pool are empty
 * STOP -> TIDYING
 *    When pool is empty
 * TIDYING -> TERMINATED
 *    When the terminated() hook method has completed
 *
 * Threads waiting in awaitTermination() will return when the
 * state reaches TERMINATED.

老污的猫
30 声望5 粉丝