线程的六种状态:
- New
- Runnable
- Blocked
- Waiting
- Timed Waiting
- Terminated
状态之间的关系如下:
验证
首先验证 New,Runnable,Terminated 三个状态。
public class NewRunnableTerminated implements Runnable {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new NewRunnableTerminated());
// 线程新建则进入 NEW
System.out.println(thread.getState());
// 程序运行就进入 Runnable
thread.start();
System.out.println(thread.getState());
// 程序运行中的状态也是 Runnable,这个 sleep 的时间要稍短,不能等线程执行结束在调用
Thread.sleep(1);
System.out.println(thread.getState());
// 程序运行结束状态是 Terminated,这个 sleep 的时间要稍长,等线程执行结束
Thread.sleep(100);
System.out.println(thread.getState());
}
@Override
public void run() {
int j = 0;
for (int i = 0; i < 10000000; i++) {
j++;
}
}
}
验证 Block,WaitingTimed,Waiting 三个状态。
public class BlockWaitingTimedWaiting implements Runnable {
public static void main(String[] args) throws InterruptedException {
BlockWaitingTimedWaiting runnable = new BlockWaitingTimedWaiting();
Thread thread1 = new Thread(runnable);
thread1.start();
Thread thread2 = new Thread(runnable);
thread2.start();
// 打印 TimedWaiting 状态,因为正在 sleep
System.out.println(thread1.getState());
// 打印 blocked 状态,因为 thread2 想拿锁拿不到。
System.out.println(thread2.getState());
// 等待时间稍长,让子线程运行 wait()
Thread.sleep(1300);
System.out.println(thread1.getState());
}
@Override
public void run() {
syn();
}
private synchronized void syn() {
try {
Thread.sleep(1000);
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
总结
- 如上图所示,左侧的三个状态是从上往下的,是不能回去的。右侧的三个状态则是可以反复进入的。
- 一般习惯,把 Blocked,Waiting,TimedWaiting 都成为阻塞状态。