I’ve been learning about concurrency in Java, and I came across the producer-consumer problem. 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. 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. Thread B, however, cannot enter take, because it’s synchronized. 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
waitwill release the lock acquired when entering the method. So if A enteredputand calledwait, the lock is released and B can then proceed insidetake.From the javadoc: