如果我们在等待之前立即使用通知会有什么缺点 [英] what will be the disadvantage if we will use notify immediately before wait

查看:39
本文介绍了如果我们在等待之前立即使用通知会有什么缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读这篇Java:notify() vs. notifyAll() 重新开始.xagyg 在那里给出了一个很好的例子.我只是想知道如果我在像下面这样的等待之前立即通知,它会解决死锁问题吗?请解释.

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)

}

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

推荐答案

我想我明白了,如果我们先通知,那么可能所有线程都会醒来并尝试访问同步函数,但等待是没有被调用所以它仍然被锁定.只有调用wait才会释放锁,所以又是死锁.

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.

这篇关于如果我们在等待之前立即使用通知会有什么缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆