是“原子”中断检查可能在java? [英] Is an "atomic" interrupt check possible in java?
问题描述
如果在Java中使用以下idiom中断,例如从此答案。
while(!Thread.currentThread()。isInterrupted()){
try {
= queue.take();
handle(value);
} catch(InterruptedException e){
Thread.currentThread()。interrupt();
}
}
其中 take 是一个阻塞操作,可以暂时忽略中断如果在 Thread.currentThread()。isInterrupted()
和调用 queue.take()
?这不是检查比行动操作吗?
有可能使用超时时间因此
我会交换try / catch和while循环:
try {
while ){
Object value = queue.take();
handle(value);
}
} catch(InterruptedException e){
Thread.currentThread()。interrupt();
}
take()
操作将立即抛出 InterruptedException
,并且同时突破while循环。
If using following "idiom" with interruption in Java, for example from this answer.
while (!Thread.currentThread().isInterrupted()) {
try {
Object value = queue.take();
handle(value);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
Where take is a blocking operation, can an interrupt not be ignored for the time being if an interrupt "arrives" between the check of Thread.currentThread().isInterrupted()
and the call queue.take()
? Is this not a "check-than-act" operation? If so, can it somehow be guaranteed that the loop is left in any case if the thread is interrupted?
It is possible to use poll with a timeout so that the loop is left after the timeout, but is it possible to check the interrupted status and act on it atomically?
I would swap the try/catch and while loop:
try {
while (true) {
Object value = queue.take();
handle(value);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
The take()
operation will throw an InterruptedException
immediately if the thread is interrupted, and at the same time break out of the while loop.
这篇关于是“原子”中断检查可能在java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!