美文网首页
5.5、观察线程状态

5.5、观察线程状态

作者: 金石_832e | 来源:发表于2021-12-08 10:32 被阅读0次
    package com.example.demo.thread;
    
    /**
     * @projectName: demo
     * @package: com.example.demo.thread
     * @className: TestState
     * @author:
     * @description: 观察线程状态
     * @date: 2021/12/7 21:35
     */
    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) {
                        e.printStackTrace();
                    }
                }
            });
    
            // 线程状态
            Thread.State state = thread.getState();
            System.out.println(state);
    
            thread.start();
            state = thread.getState();
            System.out.println(state);
    
            while (thread.isAlive()){
                state = thread.getState();
                Thread.sleep(1000);
                System.out.println(state);
            }
    
            state = thread.getState();
            System.out.println(state);
    
            // 会出现异常:死亡的线程不能再次启动!!!
            thread.start();
        }
    }
    

    image.png

    相关文章

      网友评论

          本文标题:5.5、观察线程状态

          本文链接:https://www.haomeiwen.com/subject/jqaaxrtx.html