一、6种生命周期介绍
New:已创建未启动的线程。 new Thread,还没执行start方法,这时候它已经做了一些准备工作。
Runnable: 一旦调用了start方法,就到了runnable。不一定拿到系统资源(对应操作系统中的 ready和running)cpu资源又被拿走,也是runnable状态
Blocked: 当线程处在synchronized代码块,该锁已经被其他代码块拿走了(monitor已经被其他线程拿走了)线程的状态就是Blocked。仅仅针对synchronized修饰的。
Waiting:没有设置Timeout参数的Object.wait()方法。
Timed Waiting: 有时间期限的等待,比Waiting多了一个时间参数。
Terminated:已终止。正常运行完,或者出现了一个没有捕获的异常,异常终止。
以下是线程状态间的转化图示:
线程的6个状态.png
下面演示NEW, RUNNABLE,TERMINATED三种状态:
public class NewRunnableTerminated implements Runnable {
@Override
public void run() {
for (int i = 0; i < 300; i++) {
System.out.println(i);
}
}
public static void main(String[] args) {
Thread thread = new Thread(new NewRunnableTerminated());
System.out.println(thread.getState()); //NEW
thread.start();
System.out.println(thread.getState()); //RUNNABLE
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(thread.getState()); //RUNNABLE
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(thread.getState()); //TERMINATED
}
}
下面演示TIMED_WAITING, BLOCKED,WAITING三种状态:
public class BlockedWaitingTimedWaiting implements Runnable {
@Override
public void run() {
syn();
}
public static void main(String[] args) {
BlockedWaitingTimedWaiting runnable = new BlockedWaitingTimedWaiting();
Thread thread1 = new Thread(runnable);
thread1.start();
Thread thread2 = new Thread(runnable);
thread2.start();
System.out.println(thread1.getState());//打印出 TIMED_WAITING,因为正在执行Thread.sleep(1000);
System.out.println(thread2.getState());//打印出BLOCKED状态,因为thread2想拿到sync()的锁却拿不到
try {
Thread.sleep(1300);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(thread1.getState());//WAITING
}
private synchronized void syn() {
try {
Thread.sleep(1000);
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果:
TIMED_WAITING
BLOCKED
WAITING
二、阻塞状态是什么?
一般习惯而言,把Blocked(被阻塞)、Waiting(等待)、Timed_waiting(计时等待)都称为阻塞状态。不仅仅是Blocked。概念源自《Java并发实战》