观测线程状态

package state;

public class TestState {
    public static void main(String[] args) {
        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("/////////");
        });


        //观察创建时
        System.out.println(thread.getState());//NEW

        //观察启动后
        thread.start();//开启线程(线程里先做睡眠循环,最后做输出)
        System.out.println(thread.getState());//RUN

        while (thread.getState()!=Thread.State.TERMINATED){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);

            }
            System.out.println(thread.getState());
        }
    }
}
posted @ 2023-03-10 20:59  北极有熊ovo  阅读(14)  评论(0)    收藏  举报