ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

观测线程状态

2026/8/20 15:54:24 拓冰建站 浏览量
观测线程状态

image

Thread.State state = thread.getState();

package com.guo.demo03.state;//观察测试线程的状态
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) {throw new RuntimeException(e);}}System.out.println("///////");});//观察状态Thread.State state = thread.getState();System.out.println(state); //NEW//观察启动后thread.start();state = thread.getState();System.out.println(state); //START//只要线程不终止,就一直输出状态while (state!=Thread.State.TERMINATED){thread.sleep(100);state = thread.getState();//更新状态System.out.println(state);//输出状态}thread.start();//IllegalThreadStateException  死亡之后的线程不能再次启动了}}