線程狀態
NEW:剛創建未啟動的線程
RUNNABLE:正在執行狀態
BLOCKED:處於阻塞狀態的線程
WAITING:正在等待另一個線程執行特定動作的線程
TIMED_WAITING:等待另一個線程執行時間到達指定時間
TERMINATED:線程退出執行
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);//Run狀態 while (state!=Thread.State.TERMINATED){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } state = thread.getState();//更新線程狀態 System.out.println(state);//輸出狀態 } } }
線程禮讓
當前正在執行的線程暫停,但是不會阻塞
當前線程失去處理機,編程就緒狀態
禮讓是否成功取決於CPU,如果禮讓成功,則等待下一次調度
public class TestYield { public static void main(String[] args) { MyYield myYield = new MyYield(); new Thread(myYield,"a").start(); new Thread(myYield,"b").start(); } } class MyYield implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()+"線程開始執行"); Thread.yield(); System.out.println(Thread.currentThread().getName()+"線程停止執行"); } }
[zmcjlove ] Java線程狀態變換過程代碼解析已經有265次圍觀