問題1 為什麽是while 而不是if
大多數人都知道常見的使用synchronized代碼:
synchronized (obj) { while (check pass) { wait(); } // do your business }
那麽問題是為啥這裏是while而不是if呢?
這個問題 我最開始也想了很久, 按理來說 已經在synchronized塊裏面了嘛 就不需要了. 這個也是我前面一直是這麽認為的, 直到最近看了一個Stackoverflow上的問題, 才對這個問題有了比較深入的理解.
實現一個有界隊列
試想我們要試想一個有界的隊列. 那麽常見的代碼可以是這樣:
static class Buf { private final int MAX = 5; private final ArrayList<Integer> list = new ArrayList<>(); synchronized void put(int v) throws InterruptedException { if (list.size() == MAX) { wait(); } list.add(v); notifyAll(); } synchronized int get() throws InterruptedException { // line 0 if (list.size() == 0) { // line 1 wait(); // line2 // line 3 } int v = list.remove(0); // line 4 notifyAll(); // line 5 return v; } synchronized int size() { return list.size(); } }
註意到這裏用的if, 那麽我們來看看它會報什麽錯呢?
下面的代碼用了1個線程來put ; 10個線程來get:
final Buf buf = new Buf(); ExecutorService es = Executors.newFixedThreadPool(11); for (int i = 0; i < 1; i++) es.execute(new Runnable() { @Override public void run() { while (true ) { try { buf.put(1); Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); break; } } } }); for (int i = 0; i < 10; i++) { es.execute(new Runnable() { @Override public void run() { while (true ) { try { buf.get(); Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); break; } } } }); } es.shutdown(); es.awaitTermination(1, TimeUnit.DAYS);
這段代碼很快或者說一開始就會報錯
Java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.rangeCheck(ArrayList.java:653) at java.util.ArrayList.remove(ArrayList.java:492) at TestWhileWaitBuf.get(TestWhileWait.java:80)atTestWhileWait2.run(TestWhileWait.java:47) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745)
很明顯,在remove’的時候報錯了.
那麽我們來分析下:
假設現在有A, B兩個線程來執行get 操作, 我們假設如下的步驟發生了:
1. A 拿到了鎖 line 0
2. A 發現size==0, (line 1), 然後進入等待,並釋放鎖 (line 2)
3. 此時B拿到了鎖, line0, 發現size==0, (line 1), 然後進入等待,並釋放鎖 (line 2)
4. 這個時候有個線程C往裏面加了個數據1, 那麽 notifyAll 所有的等待的線程都被喚醒了.
5. AB 重新獲取鎖, 假設 又是A拿到了. 然後 他就走到line 3, 移除了一個數據, (line4) 沒有問題.
6. A 移除數據後 想通知別人, 此時list的大小有了變化, 於是調用了notifyAll (line5), 這個時候就把B給喚醒了, 那麽B接著往下走.
7. 這時候B就出問題了, 因為 其實 此時的競態條件已經不滿足了 (size==0). B以為還可以刪除就嘗試去刪除, 結果就跑了異常了.
那麽fix很簡單, 在get的時候加上while就好了:
synchronized int get() throws InterruptedException { while (list.size() == 0) { wait(); } int v = list.remove(0); notifyAll(); return v; }
同樣的, 我們可以嘗試修改put的線程數 和 get的線程數來 發現如果put裏面不是while的話 也是不行的:
我們可以用一個外部周期性任務來打印當前list的大小, 你會發現大小並不是固定的最大5:
final Buf buf = new Buf(); ExecutorService es = Executors.newFixedThreadPool(11); ScheduledExecutorService printer = Executors.newScheduledThreadPool(1); printer.scheduleAtFixedRate(new Runnable() { @Override public void run() { system.out.println(buf.size()); } }, 0, 1, TimeUnit.SECONDS); for (int i = 0; i < 10; i++) es.execute(new Runnable() { @Override public void run() { while (true ) { try { buf.put(1); Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); break; } } } }); for (int i = 0; i < 1; i++) { es.execute(new Runnable() { @Override public void run() { while (true ) { try { buf.get(); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); break; } } } }); } es.shutdown(); es.awaitTermination(1, TimeUnit.DAYS);
這裏 我想應該說清楚了為啥必須是while 還是if了
問題2:什麽時候用notifyAll或者notify
大多數人都會這麽告訴你:
當你想要通知所有人的時候就用notifyAll, 當你只想通知一個人的時候就用notify.
但是我們都知道notify實際上我們是沒法決定到底通知誰的(都是從等待集合裏面選一個). 那這個還有什麽存在的意義呢?
在上面的例子中,我們用到了notifyAll, 那麽下面我們來看下用notify是否可以工作呢?
那麽代碼變成下面的樣子:
synchronized void put(int v) throws InterruptedException { if (list.size() == MAX) { wait(); } list.add(v); notify(); } synchronized int get() throws InterruptedException { while (list.size() == 0) { wait(); } int v = list.remove(0); notify(); return v; }
下面的幾點是jvm告訴我們的:
- 任何時候,被喚醒的來執行的線程是不可預知. 比如有5個線程都在一個對象上, 實際上我不知道 下一個哪個線程會被執行.
- synchronized語義實現了有且只有一個線程可以執行同步塊裏面的代碼.
那麽我們假設下面的場景就會導致死鎖:
P – 生產者 調用put
C – 消費者 調用get
1. P1 放了一個數字1
2. P2 想來放,發現滿了,在wait裏面等了
3. P3 想來放,發現滿了,在wait裏面等了
4. C1想來拿, C2, C3 就在get裏面等著
5. C1開始執行, 獲取1, 然後調用notify 然後退出
- 如果C1把C2喚醒了, 所以P2 (其他的都得等.)只能在put方法上等著. (等待獲取synchoronized (this) 這個monitor)
- C2 檢查while循環 發現此時隊列是空的, 所以就在wait裏面等著
- C3 也比P2先執行, 那麽發現也是空的, 只能等著了.
6. 這時候我們發現P2 , C2, C3 都在等著鎖. 最終P2 拿到了鎖, 放一個1, notify,然後退出.
7. P2 這個時候喚醒了P3, P3發現隊列是滿的,沒辦法,只能等它變為空.
8. 這時候, 沒有別的調用了, 那麽現在這三個線程(P3, C2,C3)就全部變成suspend了.也就是死鎖了.
Reference:
- http://stackoverflow.com/questions/37026/java-notify-vs-notifyall-all-over-again
Tags: synchronized 問題 list line notifyAll while
文章來源: