Java测试线程的状态

java线程的五种状态

线程通常都有五种状态:创建、就绪、运行、阻塞和死亡。

package Thread;

public class TextState {
    public static void main(String[] args) {
        Thread thread = new Thread(()->{//lambda表达式
            for (int i = 0; i < 200; i++) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("");
        });
        //观察线程状态
        Thread.State state = thread.getState();
        System.out.println(state);

        //观察启动后线程状态
        thread.start();
        state = thread.getState();
        System.out.println(state);

        while (state!=Thread.State.TERMINATED){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            state = thread.getState();
            System.out.println(state);
        }
    }
}

你可能感兴趣的:(Java)