为什么必须wait()总是在同步块中 [英] Why must wait() always be in synchronized block

查看:537
本文介绍了为什么必须wait()总是在同步块中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道,为了调用 Object.wait() ,此调用必须放在同步块中,否则 IllegalMonitorStateException 被抛出。 我知道 wait()释放监视器,但为什么我们需要显式地获取监视器使特定块同步,然后通过调用 wait()


释放监视器。可以在同步块外调用 wait(),保留它的语义 - 挂起调用程序线程?

解决方案

wait() ,所以它总是关于线程之间的通信,并且需要同步工作正常。可以认为这应该是隐含的,但是这不会真正帮助,原因如下:



语义上,你从不只是 wait 。你需要一些条件来满足,如果不是,你等到它是。所以你真正做的是

  if(!condition){
wait
}

但是条件是由一个单独的线程设置的,这个工作正确,你需要同步。



一个更多的问题,它只是因为你的线程退出等待并不意味着你正在寻找的条件是真的:




  • 您可以得到虚假的唤醒(意味着线程可以在没有收到通知的情况下等待唤醒) / p>


  • 条件可以设置,但是第三个线程在等待线程唤醒时重新使条件为false(并重新获取监视器)。




要处理这些情况,您真正需要的是

 同步(锁定){
while(!condition){
lock.wait
}
}

更好的是,不要搞乱同步原语并且使用 java.util.concurrent 包中提供的抽象。


We all know that in order to invoke Object.wait(), this call must be placed in synchronized block, otherwise an IllegalMonitorStateException is thrown. But what's the reason for making this restriction? I know that wait() releases the monitor, but why do we need to explicitly acquire the monitor by making particular block synchronized and then release the monitor by calling wait()?

What is the potential damage if it was possible to invoke wait() outside a synchronized block, retaining it's semantics - suspending the caller thread?

解决方案

A wait() only makes sense when there is also a notify(), so it's always about communication between threads, and that needs synchronization to work correctly. One could argue that this should be implicit, but that would not really help, for the following reason:

Semantically, you never just wait(). You need some condition to be satsified, and if it is not, you wait until it is. So what you really do is

if(!condition){
    wait();
}

But the condition is being set by a separate thread, so in order to have this work correctly you need synchronization.

A couple more things wrong with it, where just because your thread quit waiting doesn't mean the condition you are looking for is true:

  • You can get spurious wakeups (meaning that a thread can wake up from waiting without ever having received a notification), or

  • The condition can get set, but a third thread makes the condition false again by the time the waiting thread wakes up (and reacquires the monitor).

To deal with these cases what you really need is always some variation of this:

synchronized(lock){
    while(!condition){
        lock.wait();
    }
}

Better yet, don't mess with the synchronization primitives at all and work with the abstractions offered in the java.util.concurrent packages.

这篇关于为什么必须wait()总是在同步块中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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