线程池包含哪些状态

参考答案

1.   线程池5种状态

1.1   RUNNING

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

1.2  SHUTDOWN

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

1.3   STOP

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

1.4  TIDYING

  • SHUTDOWN 状态下,任务数为 0, 其他所有任务已终止,线程池会变为 TIDYING 状态,会执行 terminated() 方法。线程池中的 terminated() 方法是空实现,可以重写该方法进行相应的处理。
  • 线程池在 SHUTDOWN 状态,任务队列为空且执行中任务为空,线程池就会由 SHUTDOWN 转变为 TIDYING 状态。
  • 线程池在 STOP 状态,线程池中执行中任务为空时,就会由 STOP 转变为 TIDYING 状态。

1.5   TERMINATED

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

ThreadPoolExecutor 源码:

// runState is stored in the high-order bits
private 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;

2. 线程池状态转换

线程池包含哪些状态

3. JDK 源码中的解释

状态:

The runState provides the main lifecyle 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

状态间的变化:

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.

以上,是Java面试题【线程池包含哪些状态】的参考答案。

 

输出,是最好的学习方法

欢迎在评论区留下你的问题、笔记或知识点补充~

—end—

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧