多线程使Java方法不可中断的用例是什么
我在看谷歌番石榴。在等待新的许可证时,acquire方法将把线程置于uninterruptibleuninterruptible睡眠状态。中断异常
不间断的睡眠并不能完全忽略中断异常。但只要抓住它,记住它已经被打断,然后继续睡眠,直到达到超时。它最终会很好地将中断标志设置回线程
列表项
- 这可以防止来电者通过中断来取消等待。它可能有什么好处?是否只是因为该方法不知道如何强制调用方处理InterruptedException李>
- 我们可能希望使用相同模式的不间断代码的其他用例有哪些李>
编辑: 我才意识到我把它和错误的方法联系起来了
public static boolean awaitUninterruptibly(Condition condition, long timeout, TimeUnit unit)
正确的方法是不间断地睡眠
public static void sleepUninterruptibly(long sleepFor, TimeUnit unit) {
boolean interrupted = false;
try {
long remainingNanos = unit.toNanos(sleepFor);
long end = System.nanoTime() + remainingNanos;
while (true) {
try {
// TimeUnit.sleep() treats negative timeouts just like zero.
NANOSECONDS.sleep(remainingNanos);
return;
} catch (InterruptedException e) {
interrupted = true;
remainingNanos = end - System.nanoTime();
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
# 1 楼答案
呼叫者将不会收到
InterruptedException
Thread.currentThread().interrupt();
只设置一个内部标志,它不会抛出InterruptedException
可能有(我不知道是真的)情况下,等待而不被打断是有意义的。我确实知道一种理论上的中断可能会因为“虚假中断”而发生,即:没有真正原因的中断直接依赖于您的代码,如文档所示here: