- NEW:尚未启动的线程处于此状态
- RUNNABLE:执行的线程处于此状态
- BLOCKED:被阻塞等待时锁定的线程处于此状态
- WAITING:正在等待另一个线程执行特定的线程处在此状态
- TIMED_WAITNG:正在等待另一个线程执行动作达到指定等待时间的线程处于此状态
- TERMINATED:已退出的线程处于此状态
package StateThread;
//观察测试线程的状态
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(100);
} 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);//Run
while (state != Thread.State.TERMINATED){//只要线程不停止,就一直输出状态
Thread.sleep(10);
state = thread.getState();//更新线程状态
System.out.println(state);//输出状态
}
}
}
![image](https://img2024.cnblogs.com/blog/3399144/202404/3399144-20240408213044946-1043874288.png)