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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/556314.html
標籤:其他
上一篇:C++面試八股文:什么是建構式?
下一篇:返回列表