在java中可以进行“原子”中断检查吗?
发布时间:2020-12-15 03:03:16 所属栏目:Java 来源:网络整理
导读:如果在 Java中使用以下“idiom”中断,例如 from this answer. while (!Thread.currentThread().isInterrupted()) { try { Object value = queue.take(); handle(value); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }} 在take
如果在
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循环. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |