此代码来自Java Concurrency In Practice,并且讨论的是Noncancelable任务。我无法弄清楚finally
块中的代码何时会运行,除非抛出其他异常,否则while(true)
循环不会永远继续吗?
/**
* NoncancelableTask
* <p/>
* Noncancelable task that restores interruption before exit
*
* @author Brian Goetz and Tim Peierls
*/
public class NoncancelableTask {
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();
}
}
interface Task {
}
}