简体   繁体   English

对生产者 - 消费者解决方案感到困惑(同步澄清)

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

I've been learning about concurrency in Java, and I came across the producer-consumer problem. 我一直在学习Java中的并发性,并且遇到了生产者 - 消费者问题。 It's apparently standard, and I've seen a near identical answer in many places. 它显然是标准的,我在许多地方看到了几乎相同的答案。

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;
}

My understanding of synchronized is that it uses an object-wide lock, meaning that threads couldn't be in both put and take. 我对synchronized的理解是它使用了一个对象范围的锁,意味着线程不能同时放入和取出。 But, both methods wait for the other method. 但是,两种方法都在等待另一种方法。 This is where I'm confused: this seems to create deadlock. 这是我困惑的地方:这似乎造成了僵局。 If thread A goes into put while empty=false , it'll wait. 如果线程A进入put while empty=false ,它将等待。 Thread B, however, cannot enter take, because it's synchronized. 但是,线程B无法进入take,因为它是同步的。 Therefore empty will be false forever, giving deadlock. 因此空虚将永远是虚假的,给予僵局。

Given how many times I've basically seen this answer, however, it seems like it must be right. 然而,鉴于我基本上看到了这个答案的次数,它似乎一定是正确的。 What am I understanding wrong? 我理解错了什么?

Thank you! 谢谢!

Calling wait will release the lock acquired when entering the method. 调用wait将释放进入方法时获取的锁。 So if A entered put and called wait , the lock is released and B can then proceed inside take . 因此,如果输入putwait ,锁被释放,则B可以进行内take

From the javadoc : 来自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