Java多線程notify¬ifyall的區別

來源:互聯網
上載者:User

當一個線程進入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。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.