use*_*547 7 java concurrency multithreading interrupt
如果在Java中使用以下"idiom",例如从这个答案.
while (!Thread.currentThread().isInterrupted()) {
try {
Object value = queue.take();
handle(value);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
Run Code Online (Sandbox Code Playgroud)
如果take是一个阻塞操作,如果在检查Thread.currentThread().isInterrupted()
和呼叫之间有一个中断"到达",那么暂时不能忽略一个中断queue.take()
吗?这不是"检查而非行动"的操作吗?如果是这样,如果线程被中断,它是否可以保证在任何情况下都保留循环?
可以使用 带超时的轮询,以便在超时后保留循环,但是是否可以检查中断状态并以原子方式对其进行操作?
我会交换 try/catch 和 while 循环:
try {
while (true) {
Object value = queue.take();
handle(value);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
Run Code Online (Sandbox Code Playgroud)
如果线程被中断,操作take()
会立即抛出异常InterruptedException
,同时跳出while循环。