如果在
Java中使用以下“idiom”中断,例如
from this answer.
- while (!Thread.currentThread().isInterrupted()) {
- try {
- Object value = queue.take();
- handle(value);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- }
在take是阻塞操作的情况下,如果在Thread.currentThread().isInterrupted()的检查和调用queue.take()之间中断“到达”,则暂时不能忽略中断吗?这不是“检查而非行动”的行动吗?如果是这样,如果线程被中断,它是否可以保证在任何情况下都保留循环?
可以使用poll with a timeout以便在超时后保留循环,但是是否可以检查中断状态并以原子方式对其进行操作?
解决方法
我会交换try / catch和while循环:
- try {
- while (true) {
- Object value = queue.take();
- handle(value);
- }
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
如果线程被中断,take()操作将立即抛出InterruptedException,同时中断while循环.