Java wait() 不抛出 InterruptedException
我在线程 A 上有一个对象正在调用wait()
,而线程 B 上的另一个对象执行一些工作,然后调用线程 A 对象的 notify()
。然后线程 A 执行一些后处理。
我的问题非常简单:
synchronized(this)
{
while(!flag)
{
try
{
wait();
getLogger().info("No longer waiting");
}
catch (InterruptedException ie)
{
getLogger().info("Wait threw InterruptedException");
}
}
}
导致信息消息“不再等待”而不是“等待抛出 InterruptedException”。
我很困惑,因为这个 (http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#wait()):
抛出:
InterruptedException - 如果另一个线程中断了 当前线程在等待之前或期间 通知。当前线程的中断状态被清除 当抛出此异常时。
为什么我会有奇怪的行为?
谢谢。
I have an object on thread A that is calling wait()
while another object on thread B does some work then calls thread A's object's notify()
. Thread A then performs some post-processing.
My problem is pretty straightforward:
synchronized(this)
{
while(!flag)
{
try
{
wait();
getLogger().info("No longer waiting");
}
catch (InterruptedException ie)
{
getLogger().info("Wait threw InterruptedException");
}
}
}
Results in an info message of "No longer waiting" instead of "Wait threw InterruptedException".
I am confused, because of this (http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#wait()):
Throws:
InterruptedException - if another thread interrupted the
current thread before or while the current thread was waiting for a
notification. The interrupted status of the current thread is cleared
when this exception is thrown.
Why am I getting odd behavior?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当线程使用
wait()
等待时,他实际上是在等待notify()
。因此,一旦另一个线程调用了notify(),该线程将继续,如果您调用interrupt(),您将得到异常。另外,从您链接到的文档中:
notify
释放线程的锁。When a thread waits using
wait()
, he actually waits fornotify()
. So oncenotify()
has been called by the other thread, this thread will continue, if you will callinterrupt()
, you would get the exception.Also, from the documents you linked to:
notify
releases the thread from the lock.notify()
不会使wait()
抛出InterruptedException
。notify()
让wait()
继续正常的程序流程。notify()
does not makewait()
throwInterruptedException
.notify()
letwait()
continue the normal program flow.notify()
并不是wait()
线程的异常终止。例如,如果线程在调用notify()
之前终止,而不是由于调用notify()
的结果,您就会收到异常。线程并没有被中断——它已经被唤醒了。notify()
is not an abnormal termintation for a thread that iswait()
-ing. You'd get the exception if, for instance, the thread was terminated beforenotify()
was called - not as a result ofnotify()
being called. The thread hasn't been interrupted - it's been awoken.请注意,该代码中有一个错误。等待应该始终在循环中调用,并在唤醒后检查条件。
wait 可以通过虚假唤醒来唤醒。请参阅 javadoc wait()< /a>
Note that you have a bug in that code. Wait should always be invoked in a loop, and check a condition after waking up.
wait can be awaken by a spurious wakeup. See the javadoc wait()