线程状态观测
Thread.State
线程状态
-
NEW
尚未启动的线程处于此状态
-
RUNNABLE
在JAVA虚拟机中执行的线程处于此状态
-
BLOCKED
被阻塞等待监视器锁定的线程处于此状态
-
WAITING
在等待另一个线程执行特定动作的线程处于此状态
-
TIME_WAITING
正在等待另一个线程执行动作达到指定等待时间的线程处于此状态
-
TERMINATED
已退出的线程处于此状态
一个线程可以在给定时间点处于一个状态。这些状态是不反映任何操作系统线程状态的虚拟机状态
package com.faq.state;
//观察测试线程的状态
public class TestState {
public static void main(String[] args) {
Thread thread = new Thread(()->{
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} 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);//RUNNBLE
while(state != Thread.State.TERMINATED){//只要线程不终止,就一直输出状态
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
state = thread.getState();//更新线程状态
System.out.println(state);//输出状态
}
thread.start();//线程一旦死亡,就不能再调用
}
}
输出:
NEW
RUNNABLE
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
//
TERMINATED
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:708)
at com.faq.state.TestState.main(TestState.java:35)