sleep/wait/notify/notifyAll分別有什麼做用?它們的區別是什麼?wait時爲何要放在循環裏而不能直接用if?
首先對幾個相關的方法作個簡單解釋,Object中有幾個用於線程同步的方法:wait、notify、notifyAll。java
public class Object { public final native void wait(long timeout) throws InterruptedException; public final native void notify(); public final native void notifyAll(); }
sleep和wait均可以讓線程阻塞,也均可以指定超時時間,甚至還都會拋出中斷異常InterruptedException。微信
而它們最大的區別就在於,sleep時線程依然持有鎖,別人沒法進當前同步方法;wait時放棄了持有的鎖,其它線程有機會進入該同步方法。屢次提到同步方法,由於wait必須在synchronized同步代碼塊中,不然會拋出異常IllegalMonitorStateException,notify也是如此,能夠說wait和notify是就是爲了在同步代碼中作線程調度而生的。atom
下面一個簡單的例子展示sleep和wait的區別:spa
import java.util.Date; import java.util.concurrent.atomic.AtomicInteger; public class Main { // 日誌行號記錄 private AtomicInteger count = new AtomicInteger(); public static void main(String[] args) throws InterruptedException { Main main = new Main(); // 開啓兩個線程去執行test方法 new Thread(main::test).start(); new Thread(main::test).start(); } private synchronized void test() { try { log("進入了同步方法,並開始睡覺,1s"); // sleep不會釋放鎖,所以其餘線程不能進入這個方法 Thread.sleep(1000); log("睡好了,但沒事作,有事叫我,等待2s"); //阻塞在此,而且釋放鎖,其它線程能夠進入這個方法 //當其它線程調用此對象的notify或者notifyAll時纔有機會中止阻塞 //就算沒有人notify,若是超時了也會中止阻塞 wait(2000); log("我要走了,但我要再睡一覺,10s"); //這裏睡的時間很長,由於沒有釋放鎖,其它線程就算wait超時了也沒法繼續執行 Thread.sleep(10000); log("走了"); notify(); } catch (InterruptedException e) { e.printStackTrace(); } } // 打印日誌 private void log(String s) { System.out.println(count.incrementAndGet() + " " + new Date().toString().split(" ")[3] + "\t" + Thread.currentThread().getName() + " " + s); } } /* 輸出: 1 00:13:23 Thread-0 進入了同步方法,並開始睡覺,1s 2 00:13:24 Thread-0 睡好了,但沒事作,有事叫我,等待2s 3 00:13:24 Thread-1 進入了同步方法,並開始睡覺,1s 4 00:13:25 Thread-1 睡好了,但沒事作,有事叫我,等待2s 5 00:13:26 Thread-0 我要走了,但我要再睡一覺,10s 6 00:13:36 Thread-0 走了 7 00:13:36 Thread-1 我要走了,但我要再睡一覺,10s 8 00:13:46 Thread-1 走了 */
對輸出作個簡單解釋(已經看懂代碼的童鞋能夠跳過):線程
1 00:13:23 Thread-0 進入了同步方法,並開始睡覺,1s // Thread-0首先進入同步方法,Thread-1只能門外候着 2 00:13:24 Thread-0 睡好了,但沒事作,有事叫我,等待2s // Thread-0 sleep 1秒這段時間,Thread-1沒進來,證實sleep沒有釋放鎖 3 00:13:24 Thread-1 進入了同步方法,並開始睡覺,1s // Thread-0開始wait後Thread-1立刻就進來了,證實wait釋放了鎖 4 00:13:25 Thread-1 睡好了,但沒事作,有事叫我,等待2s // Thread-1也打算wait 2秒(2秒後真的能醒來嗎?) 5 00:13:26 Thread-0 我要走了,但我要再睡一覺,10s // Thread-0已經wait超時醒來了,此次準備sleep 10s 6 00:13:36 Thread-0 走了 // 10s過去了Thread-0都sleep結束了,那個說要wait 2s的Thread-1還沒動靜,證實超時也沒用,還得搶到鎖 7 00:13:36 Thread-1 我要走了,但我要再睡一覺,10s // Thread-0退出同步代碼後,Thread-1才終於獲得了鎖,能行動了 8 00:13:46 Thread-1 走了
一樣是喚醒等待的線程,一樣最多隻有一個線程能得到鎖,一樣不能控制哪一個線程得到鎖。日誌
區別在於:code
若是以爲解釋的不夠明白,代碼來一波:對象
import java.util.Date; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; public class Main { private AtomicInteger count = new AtomicInteger(); public static void main(String[] args) throws InterruptedException { Main main = new Main(); // 開啓兩個線程去執行test方法 for (int i = 0; i < 10; i++) { new Thread(main::testWait).start(); } Thread.sleep(1000); for (int i = 0; i < 5; i++) { main.testNotify(); } } private synchronized void testWait() { try { log("進入了同步方法,開始wait"); wait(); log("wait結束"); } catch (InterruptedException e) { e.printStackTrace(); } } private synchronized void testNotify() { notify(); } private void log(String s) { System.out.println(count.incrementAndGet() + " " + new Date().toString().split(" ")[3] + "\t" + Thread.currentThread().getName() + " " + s); } } /* 輸出: 1 00:59:32 Thread-0 進入了同步方法,開始wait 2 00:59:32 Thread-9 進入了同步方法,開始wait 3 00:59:32 Thread-8 進入了同步方法,開始wait 4 00:59:32 Thread-7 進入了同步方法,開始wait 5 00:59:32 Thread-6 進入了同步方法,開始wait 6 00:59:32 Thread-5 進入了同步方法,開始wait 7 00:59:32 Thread-4 進入了同步方法,開始wait 8 00:59:32 Thread-3 進入了同步方法,開始wait 9 00:59:32 Thread-2 進入了同步方法,開始wait 10 00:59:32 Thread-1 進入了同步方法,開始wait 11 00:59:33 Thread-0 wait結束 12 00:59:33 Thread-6 wait結束 13 00:59:33 Thread-7 wait結束 14 00:59:33 Thread-8 wait結束 15 00:59:33 Thread-9 wait結束 */
例子中有10個線程在wait,但notify了5次,而後其它線程一直阻塞,這也就說明使用notify時若是不能準確控制和wait的線程數對應,可能會致使某些線程永遠阻塞。開發
使用notifyAll喚醒全部等待的線程:rem
import java.util.Date; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; public class Main { private AtomicInteger count = new AtomicInteger(); public static void main(String[] args) throws InterruptedException { Main main = new Main(); // 開啓兩個線程去執行test方法 for (int i = 0; i < 5; i++) { new Thread(main::testWait).start(); } Thread.sleep(1000); main.testNotifyAll(); } private synchronized void testWait() { try { log("進入了同步方法,開始wait"); wait(); log("wait結束"); } catch (InterruptedException e) { e.printStackTrace(); } } private synchronized void testNotifyAll() { notifyAll(); } private void log(String s) { System.out.println(count.incrementAndGet() + " " + new Date().toString().split(" ")[3] + "\t" + Thread.currentThread().getName() + " " + s); } } /* 輸出: 1 01:03:24 Thread-0 進入了同步方法,開始wait 2 01:03:24 Thread-4 進入了同步方法,開始wait 3 01:03:24 Thread-3 進入了同步方法,開始wait 4 01:03:24 Thread-2 進入了同步方法,開始wait 5 01:03:24 Thread-1 進入了同步方法,開始wait 6 01:03:25 Thread-1 wait結束 7 01:03:25 Thread-2 wait結束 8 01:03:25 Thread-3 wait結束 9 01:03:25 Thread-4 wait結束 10 01:03:25 Thread-0 wait結束 */
只須要調用一次notifyAll,全部的等待線程都被喚醒,而且去競爭鎖,而後依次(無序)獲取鎖完成了後續任務。
一些源碼中出現wait時,每每都是伴隨着一個循環語句出現的,好比:
private synchronized void f() throws InterruptedException { while (!isOk()) { wait(); } System.out.println("I'm ok"); }
既然wait會被阻塞直到被喚醒,那麼用if+wait不就能夠了嗎?其餘線程發現條件達到時notify一下不就好了?
理想狀況確實如此,但實際開發中咱們每每不能保證這個線程被notify時條件已經知足了,由於極可能有某個無關(和這個條件的邏輯無關)的線程由於須要線程調度而調用了notify或者notifyAll。此時若是樣例中位置等待的線程不巧被喚醒,它就會繼續往下執行,但由於用的if,此次被喚醒就不會再判斷條件是否知足,最終程序按照咱們不指望的方式執行下去。