问题
I was reading this Java: notify() vs. notifyAll() all over again. xagyg has given a good example there. I just want to know if I put notify immediately before the wait like below, will it solve the problem of deadlock? Please explain.
while (buf.size()==MAX_SIZE) {
notify();
wait(); // called if the buffer is full (try/catch removed for brevity)
}
and
while (buf.size()==0) {
notify();
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)
}
回答1:
I think I got it, if we will notify first then it might be possible that all threads will woke up and try to access the synchronized function but as wait is not called so it is still locked. Lock will be released only by calling wait so it will be again a deadlock.
来源:https://stackoverflow.com/questions/28064462/what-will-be-the-disadvantage-if-we-will-use-notify-immediately-before-wait