国产探花免费观看_亚洲丰满少妇自慰呻吟_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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 鹤壁市| 定州市| 方山县| 沈丘县| 新密市| 类乌齐县| 建平县| 二手房| 西乡县| 沐川县| 凤阳县| 松桃| 原平市| 汶上县| 西安市| 哈密市| 四平市| 靖边县| 新泰市| 高平市| 湾仔区| 梁河县| 宁波市| 泊头市| 噶尔县| 濮阳市| 黎城县| 仙居县| 明光市| 察隅县| 嘉义市| 顺昌县| 乡城县| 晋中市| 博湖县| 贵港市| 嘉兴市| 玛纳斯县| 喜德县| 陇南市| 通山县|