我正在阅读“实践中的并发性”,在第6章的“响应中断”中说
过早设置中断状态可能导致无限循环,因为大多数可中断阻塞方法在进入时检查中断状态,如果设置了中断状态,则立即抛出InterruptedException。(可中断方法通常在阻塞或做任何重要工作之前轮询中断,以便在阻塞或做任何重要工作之前对中断作出同样的响应,从而尽可能地对中断作出响应)
public Task getNextTask(BlockingQueue<Task> queue) {
boolean interrupted = false;
try {
while (true) {
try {
return queue.take();
} catch (InterruptedException e) {
interrupted = true;
// fall through and retry
}
}
} finally {
if (interrupted)
Thread.currentThread().interrupt();
}
}假设代码是
public Task getNextTask(BlockingQueue<task> queue){
boolean interrupted=false;
while(true){
/*i get this part that before the take() function threads interrupted status is checked*/
return queue.take();
}catch(InterruptedException e){
interrupted=true;
Thread.currentThread().interrupt();
}
}//end of while
}现在,为什么最后一个函数会导致无限循环,因为我已经将threrad的中断状态设置回false,根据我的理解,在阻塞调用轮询线程的中断状态期间,它将检查它是否设置为false,然后继续调用。那么无限循环是从哪里来的呢?
发布于 2019-09-01 16:58:34
因为take()方法会检查中断,所以会抛出InterruptedException。此检查/抛出通常采用以下形式:
if (Thread.currentThread.interrupted()) { // Checks and clears the interrupted flag.
throw new InterruptedException();
}然后捕获InterruptedException,恢复中断标志,并再次调用take()。它检查中断,发现线程已被中断,然后抛出InterruptedException。
然后捕获InterruptedException,恢复中断标志,并再次调用take()。它检查中断,发现线程已被中断,然后抛出InterruptedException。
然后捕获InterruptedException,恢复中断标志,并再次调用take()。它检查中断,发现线程已被中断,然后抛出InterruptedException。
等。
https://stackoverflow.com/questions/57744188
复制相似问题