线程状态观测
大约 1 分钟Java多线程详解
Thread. State
public static enum Thread.State
extends Enum<Thread.State>
A thread state. A thread can be in one of the following states:
NEW
A thread that has not yet started is in this state.
RUNNABLE
A thread executing in the Java virtual machine is in this state.
BLOCKED
A thread that is blocked waiting for a monitor lock is in this state.
WAITING
A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
TIMED_WAITING
A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
TERMINATED
A thread that has exited is in this state.
A thread can be in only one state at a given point in time. These states are virtual machine states which do not reflect any operating system thread states.
线程状态。线程可以处于以下状态之一:
- NEW 尚未启动的线程处于此状态
- RUNNABLE 在Java虚拟机中执行的线程处于此状态。
- BLOCKED 被阻塞等待监视器锁定的线程处于此状态
- WAITING 正在等待另一个线程执行特定动作的线程处于此状态
- TIMED WAITING 正在等待另一个线程执行动作达到指定等待时间的线程处于此状态。
- TERMINATED 已退出的线程处于此状态。
一个线程可以在给定时间点处于一个状态。这些状态是不反映任何操作系统线程状态的虚拟机状态。
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) {
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(100);
// 更新线程状态
state = thread.getState();
System.out.println(state);
}
}
}