Thread.State

Thread的6种状态对应了Thread.State的一个枚举类

 public static enum State {
   
        NEW,
        RUNNABLE,
        BLOCKED,
        WAITING,
        TIMED_WAITING,
        TERMINATED;

        private State() {
   
        }
    }
  • NEW 新生状态
  • RUNNABLE 可运行状态
  • BLOCK 堵塞状态
  • WAITING 永久等待状态
  • TIMED_WAITING 即使等待状态
  • TERMINATED 终止状态
状态 产生场景(不唯一)
NEW 新建 new Thread后
RUNNABLE 线程调用start()方法后
BLOCKED IO堵塞.锁堵塞🔒等情况
WAITING 线程调用wait()方法后,需要调用notify()或notifyAll()方法才可以唤醒或者等待一个死循环线程体
TIME WAITING 线程调用sleep()方法后,或者join(long)
TERMINATED 线程调用yield()方法后或者正常结束运行的线程

6种状态重现:

@Slf4j(topic = "c.Test11")
public class Test11 {
   
    public static void main(String[] args) {
   
        //NEW
        Thread t1 = new Thread(){
   
            @Override
            public void run() {
   
                log.debug("running");
            }
        };

        //RUNNABLE
        Thread t2 = new Thread(){
   
            @Override
            public void run() {
   
                while(true){
   

                }
            }
        };
        t2.start();

        //WAITING
        Thread t3 = new Thread(){
   
            @Override
            public void run() {
   
                try {
   
                    t2.join();
                } catch (InterruptedException e) {
   
                    e.printStackTrace();
                }
            }
        };
        t3.start();

        //TIMED_WAITING
        Thread t4 = new Thread(){
   
            @Override
            public void run() {
   
                synchronized (Test11.class){
   
                    try {
   
                        Thread.sleep(1000000);
                    } catch (InterruptedException e) {
   
                        e.printStackTrace();
                    }
                }
            }
        };
        t4.start();

        //BLOCK
        Thread t5 = new Thread(){
   
            @Override
            public void run() {
   
                synchronized (Test11.class){
   
                    log.debug("...");
                }
            }
        };
        t5.start();

        //TERMINATED
        Thread t6 = new Thread(){
   
            @Override
            public void run() {
   
                log.debug("...");
            }
        };
        t6.start();

        //输出各自状态
        log.debug(t1.getState().toString());
        log.debug(t2.getState().toString());
        log.debug(t3.getState().toString());
        log.debug(t4.getState().toString());
        log.debug(t5.getState().toString());
        log.debug(t6.getState().toString());
    }
}

输出: