# 6 sleep與yield的比較 ## sleep 1. 調用 sleep 會讓當前線程從 *Running* 進入 *Timed Waiting* 狀態(阻塞) 2. 其它線程可以使用 interrupt 方法打斷正在睡眠的線程,這時 sleep 方法會拋出 InterruptedExcept ...
6 sleep與yield的比較
sleep
-
調用 sleep 會讓當前線程從 Running 進入 Timed Waiting 狀態(阻塞)
-
其它線程可以使用 interrupt 方法打斷正在睡眠的線程,這時 sleep 方法會拋出 InterruptedException
-
睡眠結束後的線程未必會立刻得到執行
-
建議用 TimeUnit 的 sleep 代替 Thread 的 sleep 來獲得更好的可讀性
yield
-
調用 yield 會讓當前線程從 Running 進入 Runnable 就緒狀態,然後調度執行其它線程 。同時,該線程在就緒狀態時,CPU可能會分配資源給它,使其進入運行態。
-
具體的實現依賴於操作系統的任務調度器
yield和線程優先順序代碼實例
//代碼實例 public class YieldAndPriority { public static void main(String[] args) { Runnable task1 = new Runnable() { @Override public void run() { int count = 0; //yield,讓線程進入就緒態,CPU可能會調度該線程,使得該線程變為執行狀態 Thread.yield(); while (true) { System.out.println("-------> task1 count=" + count++); } } }; Runnable task2 = new Runnable() { @Override public void run() { int count = 0; while (true) { System.out.println(" --------------------------------------> task2 count=" + count++); } } }; Thread t1 = new Thread(task1, "t1"); Thread t2 = new Thread(task2, "t2"); //設置優先順序1-10 越大優先順序越高 t1.setPriority(1); t2.setPriority(10); t1.start(); t2.start(); } }
//輸出結果 ... --------------------------------------> task2 count=34436 --------------------------------------> task2 count=34437 --------------------------------------> task2 count=34438 --------------------------------------> task2 count=34439 --------------------------------------> task2 count=34440 --------------------------------------> task2 count=34441 --------------------------------------> task2 count=34442 --------------------------------------> task2 count=34443 --------------------------------------> task2 count=34444 -------> task1 count=42407 -------> task1 count=42408 -------> task1 count=42409 -------> task1 count=42410 -------> task1 count=42411 -------> task1 count=42412 -------> task1 count=42413 -------> task1 count=42414 -------> task1 count=42415 -------> task1 count=42416 進程已結束,退出代碼130