考虑 java.util.concurrent.locks.AbstractQueuedSynchronizer 中的以下代码作为标题中提出的想法的众多示例之一:
1258 public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout) throws Interrupted Exception {
1259 if (Thread.interrupted())
1260 throw new InterruptedException();
1261 return tryAcquireShared(arg) >= 0 ||
1262 doAcquireSharedNanos(arg, nanosTimeout);
1263 }
为什么大多数阻塞库方法通过调用静态方法 Thread.interrupted()
而不是实例方法 isInterrupted()
来响应中断。调用静态方法也会清除中断状态,因此即使任务处理代码吞掉了 InterruptionException ,调用者也无法了解除了
最佳答案
如果您捕获 InterruptedException
,则中断标志已被清除,这始终是正确的。异常(exception)本身就是您当时的信号机制。捕手需要重新启用标志或直接处理线程关闭。
关于java - 为什么阻塞库方法经常通过调用静态interrupted()而不是实例方法isInterrupted()来响应中断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11501150/