观测线程状态

image

Thread.State state = thread.getState();

package com.guo.demo03.state;

//观察测试线程的状态
public class TestState {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("///////");
        });
        //观察状态
        Thread.State state = thread.getState();
        System.out.println(state); //NEW

        //观察启动后
        thread.start();
        state = thread.getState();
        System.out.println(state); //START

        //只要线程不终止,就一直输出状态
        while (state!=Thread.State.TERMINATED){

                thread.sleep(100);
                state = thread.getState();//更新状态
                System.out.println(state);//输出状态

        }
        thread.start();//IllegalThreadStateException  死亡之后的线程不能再次启动了
    }

}

posted @ 2026-03-25 10:39  果子同志  阅读(10)  评论(0)    收藏  举报