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

查看:37
本文介绍了为什么总是在循环内调用 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 中.根据您的业务需求,您可以退出或抑制异常并继续等待.

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天全站免登陆