簡體   English   中英

對生產者 - 消費者解決方案感到困惑(同步澄清)

[英]Confused on producer-consumer solution (synchronization clarification)

我一直在學習Java中的並發性,並且遇到了生產者 - 消費者問題。 它顯然是標准的,我在許多地方看到了幾乎相同的答案。

public synchronized void put(int num){
    while (!empty) {
        try{
            wait(); }
        catch {}
    }

    buffer=num;
    empty=false;
    notify();
}

public synchronized int take(){
    while (empty) {
        try{
            wait(); }
        catch {}
    }

    empty=true;
    notify();
    return buffer;
}

我對synchronized的理解是它使用了一個對象范圍的鎖,意味着線程不能同時放入和取出。 但是,兩種方法都在等待另一種方法。 這是我困惑的地方:這似乎造成了僵局。 如果線程A進入put while empty=false ,它將等待。 但是,線程B無法進入take,因為它是同步的。 因此空虛將永遠是虛假的,給予僵局。

然而,鑒於我基本上看到了這個答案的次數,它似乎一定是正確的。 我理解錯了什么?

謝謝!

調用wait將釋放進入方法時獲取的鎖。 因此,如果輸入putwait ,鎖被釋放,則B可以進行內take

來自javadoc

The current thread must own this object's monitor. The thread releases ownership 
of this monitor and waits until another thread notifies threads waiting on this 
object's monitor to wake up either through a call to the notify method or the 
notifyAll method. The thread then waits until it can re-obtain ownership of the 
monitor and resumes execution. 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM