其他分享
首页 > 其他分享> > 【多线程】观测线程状态 getState()

【多线程】观测线程状态 getState()

作者:互联网

观测线程状态 getState()

Thread.State(查看JDK帮助文档)

代码示例:

/**
 * @Description 观察测试线程的状态
 * @Author hzx
 * @Date 2022-03-26
 */
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(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("========线程执行结束========");
        });

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

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

        while (state != Thread.State.TERMINATED) {
            Thread.sleep(100);
            state = thread.getState(); //更新线程状态 (TIMED_WAITING-阻塞状态,TERMINATED-终止状态)
            System.out.println(state); //输出状态
        }

        //线程死亡后,再次启动会报错(死亡的线程不能再次启动)
//        thread.start();

    }
}

执行结果:

NEW
RUNNABLE
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
========线程执行结束========
TERMINATED

线程死亡后,再次启动报错效果:

标签:状态,getState,Thread,多线程,state,WAITING,线程,TIMED,观测线
来源: https://www.cnblogs.com/hzxll/p/16061642.html