Java synchronized 中的 while 和 notifyAll
問題1 為什么是while 而不是if
大多數(shù)人都知道常見的使用synchronized代碼:
| 1 2 3 4 5 6 | synchronized (obj) { ?????while (check pass) { ????????wait(); ????} ????// do your business } |
那么問題是為啥這里是while而不是if呢?
這個(gè)問題 我最開始也想了很久, 按理來說 已經(jīng)在synchronized塊里面了嘛 就不需要了. 這個(gè)也是我前面一直是這么認(rèn)為的, 直到最近看了一個(gè)Stackoverflow上的問題, 才對(duì)這個(gè)問題有了比較深入的理解.
實(shí)現(xiàn)一個(gè)有界隊(duì)列
試想我們要試想一個(gè)有界的隊(duì)列. 那么常見的代碼可以是這樣:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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, 那么我們來看看它會(huì)報(bào)什么錯(cuò)呢?
下面的代碼用了1個(gè)線程來put ; 10個(gè)線程來get:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 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); |
這段代碼很快或者說一開始就會(huì)報(bào)錯(cuò)
| 1 2 3 4 5 6 7 | 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’的時(shí)候報(bào)錯(cuò)了.
那么我們來分析下:
假設(shè)現(xiàn)在有A, B兩個(gè)線程來執(zhí)行g(shù)et 操作, 我們假設(shè)如下的步驟發(fā)生了:
1. A 拿到了鎖 line 0
2. A 發(fā)現(xiàn)size==0, (line 1), 然后進(jìn)入等待,并釋放鎖 (line 2)
3. 此時(shí)B拿到了鎖, line0, 發(fā)現(xiàn)size==0, (line 1), 然后進(jìn)入等待,并釋放鎖 (line 2)
4. 這個(gè)時(shí)候有個(gè)線程C往里面加了個(gè)數(shù)據(jù)1, 那么 notifyAll 所有的等待的線程都被喚醒了.
5. AB 重新獲取鎖, 假設(shè) 又是A拿到了. 然后 他就走到line 3, 移除了一個(gè)數(shù)據(jù), (line4) 沒有問題.
6. A 移除數(shù)據(jù)后 想通知?jiǎng)e人, 此時(shí)list的大小有了變化, 于是調(diào)用了notifyAll (line5), 這個(gè)時(shí)候就把B給喚醒了, 那么B接著往下走.
7. 這時(shí)候B就出問題了, 因?yàn)?其實(shí) 此時(shí)的競(jìng)態(tài)條件已經(jīng)不滿足了 (size==0). B以為還可以刪除就嘗試去刪除, 結(jié)果就跑了異常了.
那么fix很簡(jiǎn)單, 在get的時(shí)候加上while就好了:
| 1 2 3 4 5 6 7 8 | synchronized int get() throws InterruptedException { ??????while (list.size() == 0) { ??????????wait(); ??????} ??????int v = list.remove(0); ??????notifyAll(); ??????return v; ??} |
同樣的, 我們可以嘗試修改put的線程數(shù) 和 get的線程數(shù)來 發(fā)現(xiàn)如果put里面不是while的話 也是不行的:
我們可以用一個(gè)外部周期性任務(wù)來打印當(dāng)前l(fā)ist的大小, 你會(huì)發(fā)現(xiàn)大小并不是固定的最大5:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | 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); |
這里 我想應(yīng)該說清楚了為啥必須是while 還是if了
問題2:什么時(shí)候用notifyAll或者notify
大多數(shù)人都會(huì)這么告訴你:
當(dāng)你想要通知所有人的時(shí)候就用notifyAll, 當(dāng)你只想通知一個(gè)人的時(shí)候就用notify.
但是我們都知道notify實(shí)際上我們是沒法決定到底通知誰的(都是從等待集合里面選一個(gè)). 那這個(gè)還有什么存在的意義呢?
在上面的例子中,我們用到了notifyAll, 那么下面我們來看下用notify是否可以工作呢?
那么代碼變成下面的樣子:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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; ???} |
下面的幾點(diǎn)是jvm告訴我們的:
那么我們假設(shè)下面的場(chǎng)景就會(huì)導(dǎo)致死鎖:
P – 生產(chǎn)者 調(diào)用put
C – 消費(fèi)者 調(diào)用get
1. P1 放了一個(gè)數(shù)字1
2. P2 想來放,發(fā)現(xiàn)滿了,在wait里面等了
3. P3 想來放,發(fā)現(xiàn)滿了,在wait里面等了
4. C1想來拿, C2, C3 就在get里面等著
5. C1開始執(zhí)行, 獲取1, 然后調(diào)用notify 然后退出
- 如果C1把C2喚醒了, 所以P2 (其他的都得等.)只能在put方法上等著. (等待獲取synchoronized (this) 這個(gè)monitor)
- C2 檢查while循環(huán) 發(fā)現(xiàn)此時(shí)隊(duì)列是空的, 所以就在wait里面等著
- C3 也比P2先執(zhí)行, 那么發(fā)現(xiàn)也是空的, 只能等著了.
6. 這時(shí)候我們發(fā)現(xiàn)P2 , C2, C3 都在等著鎖. 最終P2 拿到了鎖, 放一個(gè)1, notify,然后退出.
7. P2 這個(gè)時(shí)候喚醒了P3, P3發(fā)現(xiàn)隊(duì)列是滿的,沒辦法,只能等它變?yōu)榭?
8. 這時(shí)候, 沒有別的調(diào)用了, 那么現(xiàn)在這三個(gè)線程(P3, C2,C3)就全部變成suspend了.也就是死鎖了.
Reference:
- http://stackoverflow.com/questions/37026/java-notify-vs-notifyall-all-over-again
總結(jié)
以上是生活随笔為你收集整理的Java synchronized 中的 while 和 notifyAll的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 8张图理解Java
- 下一篇: 编辑从字节码和 JVM 的角度解析 Ja