如何区分等待(长时间超时)退出通知或超时? [英] How to differentiate when wait(long timeout) exit for notify or timeout?
问题描述
有这个等待声明:
public final native void wait(long timeout) throws InterruptedException;
它可能会被InterruptedException或超时退出,或者因为另一个线程中调用了Notify / NotifyAll方法,异常很容易捕获但是......
It could exit by InterruptedException, or by timeout, or because Notify/NotifyAll method was called in another thread, Exception is easy to catch but...
有什么方法可以知道退出原因是超时还是通知?
There is any way to know if the exits cause was timeout or notify?
编辑:
这是一种可行的方法,(虽然我不喜欢)
This is a tricky way that could work, (although I don't like it)
long tBefore=System.currentTimeMillis();
wait(TIMEOUT);
if ((System.currentTimeMillis() - tBefore) > TIMEOUT)
{
//timeout
}
推荐答案
除非您提供一些额外的代码,否则无法区分这两者。例如,通过添加 ThreadLocal
布尔
设置为 true
仅限于 notify()
You can't differentiate between the two unless you provide some additional code. For example by adding a ThreadLocal
Boolean
that is set to true
only on notify()
但首先,您必须确保您的逻辑需要区分。
But first you must make sure your logic requires this differentiation.
这篇关于如何区分等待(长时间超时)退出通知或超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!