Home Tags Posts tagged with "线程状态"

线程状态

0 79


/**
 * @Author Chengzhi
 * @Date 2021/4/19 9:23
 * @Version 1.0
 *
 * 观察测试线程的状态
 */
public class TestState {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("你好啊!~~");
                }
            }
        });

        //观察状态
        Thread.State state = thread.getState();
        System.out.println(state);//NEW

        //观察启动后
        thread.start();
        System.out.println("当前线程状态为:" + thread.getState());//Run

        while(state != Thread.State.TERMINATED){//只要线程不终止,就一直输出状态
            Thread.sleep(100);
            state = thread.getState();//更新线程状态
            System.out.println("当前线程状态为:" + state);//输出线程状态
        }

    }
}

注意:线程死亡之后不能再调用start方法!!!(因为start是就绪,等待cpu调度即可执行而线程死亡代表线程已经结束)