清除Thread.interrupt()标志的方法

Ove*_*ack 18 java multithreading interrupt

我最近继承了一个几乎没有Thread安全性的大型Java应用程序.我目前正在努力的是让所有线程正确处理被中断而不是使用非常糟糕的Thread.stop().

问题的一部分是我不知道每个方法调用清除中断标志.

目前我知道以下将清除中断标志:

Thread.interrupted()
Thread.sleep(long)
Thread.join()
Thread.join(long)
Object.wait()
Object.wait(long)
Run Code Online (Sandbox Code Playgroud)

我还缺少什么?谢谢

Gra*_*ray 38

问题的一部分是我不知道每个方法调用清除中断标志.

重要的是要澄清以下方法通过调用它们来清除中断标志:

Thread.interrupted()
Thread.isInterrupted(true) -- added to your list
Run Code Online (Sandbox Code Playgroud)

因此,Thread.currentThread().isInterrupted()应始终使用.

以下方法将通过立即抛出中断标志来清除中断标志,InterruptedException如果它们被调用然后线程被中断或者线程已中断然后它们被调用(参见下面的junit代码).所以它不是清除标志的方法,抛出异常就是这样.

Thread.interrupted()
Thread.sleep(long)
Thread.join()
Thread.join(long)
Object.wait()
Object.wait(long)
Run Code Online (Sandbox Code Playgroud)

请注意,任何捕获代码的正确模式InterruptedException是立即重新中断线程.我们这样做是为了其他人依赖这个thread.isInterrupted()方法:

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(...)
Run Code Online (Sandbox Code Playgroud)

JUnit代码演示了一些:

try {
    ...
} catch (InterruptedException e) {
    // immediately re-interrupt the thread
    Thread.currentThread().interrupt();
    // log the exception or [likely] quit the thread
}
Run Code Online (Sandbox Code Playgroud)


axt*_*avt 14

常见的约定如下:任何抛出InterruptedException(+ Thread.interrupted())的方法都会清除中断标志.

所以,为了使你的线程中断的,你需要找到所有的地方InterruptedException没有retrowing,或恢复中断标志被逮住.由于InterruptedException是一个经过检查的例外,因此并不难.