为什么wait()总是在循环内调用 [英] Why should wait() always be called inside a loop

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

问题描述

我已经读过我们应该总是在循环中调用 wait()

I have read that we should always call a wait() from within a loop:

while (!condition) { obj.wait(); }

没有循环就可以正常工作,为什么会这样?

It works fine without a loop so why is that?

推荐答案

您不仅需要循环它,还要检查循环中的条件。 Java不保证您的线程只能通过notify()/ notifyAll()调用或正确的notify()/ notifyAll()调用来唤醒。由于此属性,无环版本可能适用于您的开发环境,并且意外地在生产环境中失败。

You need not only to loop it but check your condition in the loop. Java does not guarantee that your thread will be woken up only by a notify()/notifyAll() call or the right notify()/notifyAll() call at all. Because of this property the loop-less version might work on your development environment and fail on the production environment unexpectedly.

例如,您正在等待某些事情:

For example, you are waiting for something:

synchronized (theObjectYouAreWaitingOn) {
   while (!carryOn) {
      theObjectYouAreWaitingOn.wait();
   }
}

一个邪恶的线程出现了:

An evil thread comes along and:

theObjectYouAreWaitingOn.notifyAll();

如果邪恶的线程没有/不能搞乱 carryOn 您只需继续等待合适的客户。

If the evil thread does not/can not mess with the carryOn you just continue to wait for the proper client.

编辑:添加了更多样本。
等待可以中断。它抛出InterruptedException,你可能需要在try-catch中包装wait。根据您的业务需求,您可以退出或取消异常并继续等待。

Added some more samples. The wait can be interrupted. It throws InterruptedException and you might need to wrap the wait in a try-catch. Depending on your business needs, you can exit or suppress the exception and continue waiting.

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

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