这段代码何时终止?

时间:2016-01-12 03:22:28

标签: java concurrency

此代码来自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 {
    }
}

0 个答案:

没有答案