執行緒狀態
6個狀態定義:java.lang.Thread.State
- New: 尚未啟動的執行緒的執行緒狀態。
- Runnable: 可執行執行緒的執行緒狀態,等待CPU排程。
- Blocked: 執行緒阻塞等待監視器鎖定的執行緒狀態。處於synchronized同步程式碼塊或方法中被阻塞。
- Waiting: 等待執行緒的執行緒狀態。下列不帶超時的方式:Object.wait、Thread.join、LockSupport.park
- Timed Waiting: 具有指定等待時間的等待執行緒的執行緒狀態。下列超時的方式:Thread.sleep、Object.wait、Thread.join、LockSupport.parkNanos、LockSupport.parkUntil
常見執行緒狀態切換
新建->執行->終止
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread1當前狀態:" + Thread.currentThread().getState().toString());
System.out.println("thread1 執行了");
}
});
System.out.println("沒呼叫start方法,thread1當前狀態:" + thread1.getState().toString());
thread1.start();
Thread.sleep(2000L); // 等待thread1執行結束,再看狀態
System.out.println("等待兩秒,再看thread1當前狀態:" + thread1.getState().toString());
複製程式碼
新建->執行->等待->執行->終止
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
try {// 將執行緒2移動到等待狀態,1500後自動喚醒
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread2當前狀態:" + Thread.currentThread().getState().toString());
System.out.println("thread2 執行了");
}
});
System.out.println("沒呼叫start方法,thread2當前狀態:" + thread2.getState().toString());
thread2.start();
System.out.println("呼叫start方法,thread2當前狀態:" + thread2.getState().toString());
Thread.sleep(200L); // 等待200毫秒,再看狀態
System.out.println("等待200毫秒,再看thread2當前狀態:" + thread2.getState().toString());
Thread.sleep(3000L); // 再等待3秒,讓thread2執行完畢,再看狀態
System.out.println("等待3秒,再看thread2當前狀態:" + thread2.getState().toString());
複製程式碼
新建->執行->阻塞->執行->終止
Thread thread3 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (Demo2.class) {
System.out.println("thread3當前狀態:" + Thread.currentThread().getState().toString());
System.out.println("thread3 執行了");
}
}
});
synchronized (Demo2.class) {
System.out.println("沒呼叫start方法,thread3當前狀態:" + thread3.getState().toString());
thread3.start();
System.out.println("呼叫start方法,thread3當前狀態:" + thread3.getState().toString());
Thread.sleep(200L); // 等待200毫秒,再看狀態
System.out.println("等待200毫秒,再看thread3當前狀態:" + thread3.getState().toString());
}
Thread.sleep(3000L); // 再等待3秒,讓thread3執行完畢,再看狀態
System.out.println("等待3秒,讓thread3搶到鎖,再看thread3當前狀態:" + thread3.getState().toString());
複製程式碼