问题的一部分在于我不知道有多少方法可以清除中断标志。
需要澄清的是,以下方法只需调用它们即可清除中断标志:
Thread.interrupted()
Thread.isInterrupted(true) -- added to your list
因此,应始终使用Thread.currentThread().isInterrupted()
。
以下方法将通过立即抛出InterruptedException
来清除被中断的标志,无论它们是否被调用并且线程被中断,还是线程已经被中断然后它们被调用(请参见下面的junit代码)。因此,清除标志的不是方法本身,而是抛出异常。
您最初的列表:
Thread.interrupted()
Thread.sleep(long)
Thread.join()
Thread.join(long)
Object.wait()
Object.wait(long)
已添加至您的列表:
Thread.sleep(long, int)
Thread.join(int, long)
Thread.isInterrupted(true)
Object.wait(int, long)
BlockingQueue.put(...)
BlockingQueue.offer(...)
BlockingQueue.take(...)
BlockingQueue.poll(...)
Future.get(...)
Process.waitFor()
ExecutorService.invokeAll(...)
ExecutorService.invokeAny(...)
ExecutorService.awaitTermination(...)
CompletionService.poll(...)
CompletionService.take(...)
CountDownLatch.await(...)
CyclicBarrier.await(...)
Semaphore.acquire(...)
Semaphore.tryAcquire(...)
Lock.lockInteruptibly()
Lock.tryLock(...)
请注意,任何捕获 InterruptedException
的代码都应该立即重新中断线程。 我们这样做是为了防止其他人依赖于 thread.isInterrupted()
方法:
try {
...
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
下面是演示这些内容的JUnit代码:
assertFalse(Thread.currentThread().isInterrupted());
Thread.currentThread().interrupt();
assertTrue(Thread.currentThread().isInterrupted());
assertTrue(Thread.interrupted());
assertFalse(Thread.currentThread().isInterrupted());
Thread.currentThread().interrupt();
assertTrue(Thread.currentThread().isInterrupted());
try {
Thread.sleep(1);
fail("will never get here");
} catch (InterruptedException e) {
assertFalse(Thread.currentThread().isInterrupted());
Thread.currentThread().interrupt();
}
assertTrue(Thread.currentThread().isInterrupted());