国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

基于Java多線程notify與notifyall的區別分析

2019-11-26 16:07:06
字體:
來源:轉載
供稿:網友

當一個線程進入wait之后,就必須等其他線程notify/notifyall,使用notifyall,可以喚醒
所有處于wait狀態的線程,使其重新進入鎖的爭奪隊列中,而notify只能喚醒一個。注意,任何時候只有一個線程可以獲得鎖,也就是說只有一個線程可以運行synchronized 中的代碼,notifyall只是讓處于wait的線程重新擁有鎖的爭奪權,但是只會有一個獲得鎖并執行。

那么notify和notifyall在效果上又什么實質區別呢?
主要的效果區別是notify用得不好容易導致死鎖,例如下面提到的例子。

復制代碼 代碼如下:

public synchronized void put(Object o) {

    while (buf.size()==MAX_SIZE) {

        wait(); // called if the buffer is full (try/catch removed for brevity)

    }

    buf.add(o);

    notify(); // called in case there are any getters or putters waiting

}

復制代碼 代碼如下:

public synchronized Object get() {

    // Y: this is where C2 tries to acquire the lock (i.e. at the beginning of the method)

    while (buf.size()==0) {

        wait(); // called if the buffer is empty (try/catch removed for brevity)

        // X: this is where C1 tries to re-acquire the lock (see below)

    }

    Object o = buf.remove(0);

    notify(); // called if there are any getters or putters waiting

    return o;

}

所以除非你非常確定notify沒有問題,大部分情況還是是用notifyall。

更多詳細的介紹可以參看:
http://stackoverflow.com/questions/37026/java-notify-vs-notifyall-all-over-again

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 乐业县| 吴忠市| 兴山县| 贺州市| 枣阳市| 新余市| 荥阳市| 新安县| 沐川县| 田林县| 瓮安县| 晋州市| 晴隆县| 锦州市| 郁南县| 达尔| 土默特右旗| 中超| 东山县| 尚志市| 上饶市| 屯留县| 宁陕县| 黄梅县| 永吉县| 康马县| 绩溪县| 德令哈市| 永顺县| 囊谦县| 大安市| 怀化市| 张掖市| 博客| 麻栗坡县| 台南市| 佛山市| 山西省| 娄底市| 隆安县| 册亨县|