what will be the disadvantage if we will use notify immediately before wait

六眼飞鱼酱① 提交于 2019-12-25 14:03:56

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!