站点图标 度崩网-几度崩溃

线程池包含哪些状态?

线程池状态:

线程池的5种状态:RUNNING、SHUTDOWN、STOP、TIDYING、TERMINATED。

见 ThreadPoolExecutor 源码

// runState is stored in the high-order bitsprivate static final int RUNNING= -1 <<COUNT_BITS;private static final int SHUTDOWN =0 <<COUNT_BITS;private static final int STOP =1 <<COUNT_BITS;private static final int TIDYING=2 <<COUNT_BITS;private static final int TERMINATED =3 <<COUNT_BITS;

1. RUNNING:线程池一旦被创建,就处于RUNNING 状态,任务数为 0,能够接收新任务,对已排队的任务进行处理。

2. SHUTDOWN:不接收新任务,但能处理已排队的任务。调用线程池的 shutdown() 方法,线程池由 RUNNING 转变为 SHUTDOWN 状态。

3. STOP:不接收新任务,不处理已排队的任务,并且会中断正在处理的任务。调用线程池的 shutdownNow() 方法,线程池由(RUNNING 或 SHUTDOWN ) 转变为 STOP 状态。

4. TIDYING:

5. TERMINATED:线程池彻底终止。线程池在 TIDYING 状态执行完 terminated() 方法就会由 TIDYING 转变为 TERMINATED 状态。

状态转换如图

JDK 源码中的解释如下

状态:

The runState provides the main lifecyle control, taking on values:RUNNING:Accept new tasks and process queued tasksSHUTDOWN: Don't accept new tasks, but process queued tasksSTOP: Don't accept new tasks, don't process queued tasks,and interrupt in-progress tasksTIDYING:All tasks have terminated, workerCount is zero,the thread transitioning to state TIDYINGwill run the terminated() hook methodTERMINATED: terminated() has completed

状态间的变化

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 emptySTOP -> TIDYING When pool is emptyTIDYING -> TERMINATED When the terminated() hook method has completedThreads waiting in awaitTermination() will return when thestate reaches TERMINATED.