编程语言
首页 > 编程语言> > Java多线程13-线程观测

Java多线程13-线程观测

作者:互联网

image
Thread.State
线程状态。线程可以处于以下状态之一

一个线程可以在给定时间点处于一个状态。这些状态是不返回任何操作系统线程状态的虚拟机状态。

public class TestState {
    public static void main(String[] args) throws InterruptedException {
        Thread thread=new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    //子线程运行后休眠5秒钟
                    Thread.sleep(1000);
                } 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){
            Thread.sleep(500);//每隔0.5秒对子线程观测一次状态
            state = thread.getState();
            System.out.println(state);
        }
    }
}

实验结果

NEW
RUNNABLE
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
///////
TERMINATED

标签:状态,13,Thread,state,WAITING,线程,TIMED,多线程
来源: https://www.cnblogs.com/CnFallTime/p/15898805.html