线程及线程池状态

Posted IT-风

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程及线程池状态相关的知识,希望对你有一定的参考价值。

java中定义了线程状态有6种,源码在Thread类中定义了枚举类 State:

•NEW
 A thread that has not yet started is in this state. 

•RUNNABLE
 A thread executing in the Java virtual machine is in this state. 

•BLOCKED
 A thread that is blocked waiting for a monitor lock is in this state. 

•WAITING
 A thread that is waiting indefinitely for another thread to perform a particular action is in this state. 

•TIMED_WAITING
 A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. 

•TERMINATED
 A thread that has exited is in this state. 

 

线程池状态有五种,使用int的高3位表示:

1、RUNNING

(1) 状态说明:线程池处在RUNNING状态时,能够接收新任务,以及对已添加的任务进行处理。 
(02) 状态切换:线程池的初始化状态是RUNNING。换句话说,线程池被一旦被创建,就处于RUNNING状态,并且线程池中的任务数为0!

private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
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、 SHUTDOWN

(1) 状态说明:线程池处在SHUTDOWN状态时,不接收新任务,但能处理已添加的任务。 
(2) 状态切换:调用线程池的shutdown()接口时,线程池由RUNNING -> SHUTDOWN。

3、STOP

(1) 状态说明:线程池处在STOP状态时,不接收新任务,不处理已添加的任务,并且会中断正在处理的任务。 
(2) 状态切换:调用线程池的shutdownNow()接口时,线程池由(RUNNING or SHUTDOWN ) -> STOP。

4、TIDYING

(1) 状态说明:当所有的任务已终止,ctl记录的”任务数量”为0,线程池会变为TIDYING状态。当线程池变为TIDYING状态时,会执行钩子函数terminated()。terminated()在ThreadPoolExecutor类中是空的,若用户想在线程池变为TIDYING时,进行相应的处理;可以通过重载terminated()函数来实现。 
(2) 状态切换:当线程池在SHUTDOWN状态下,阻塞队列为空并且线程池中执行的任务也为空时,就会由 SHUTDOWN -> TIDYING。 
当线程池在STOP状态下,线程池中执行的任务为空时,就会由STOP -> TIDYING。

5、 TERMINATED

(1) 状态说明:线程池彻底终止,就变成TERMINATED状态。 
(2) 状态切换:线程池处在TIDYING状态时,执行完terminated()之后,就会由 TIDYING -> TERMINATED。

 

以上是关于线程及线程池状态的主要内容,如果未能解决你的问题,请参考以下文章

线程池的五种状态及创建线程池的几种方式

线程及线程池状态

Java线程及线程池状态

Java多线程 线程池的生命周期及运行状态

java线程池原理便懂了!♥♥

只需这篇文章java线程池原理便懂了!♥♥