3

我在理解 Java 线程中断标志的语义时遇到了一些麻烦。我的理解是,该标志只应在线程中断后为真,一旦设置为真,InterruptedException在捕获或等效物或用.interrupted(). 因此,我无法解释为什么会打印以下程序false

Thread t = new Thread() {
    @Override
    public void run() {
        try {
            // While await()ing, another thread calls t.interrupt().
            new CyclicBarrier(2).await();
        } finally {
            // I believe I should still be interrupted here, but am not...
            System.out.println(Thread.currentThread().isInterrupted());
        }
    }
};

(为简单起见排除了一些细节 - 假设可以run()抛出异常。)

4

1 回答 1

1

1) 打开 CyclicBarrier 源码,你会看到 await() 方法通过调用 Thread.currentThread().interrupt() 来重置中断标志。请参阅 doWait(),它是 wait() 的实际实现。实际上,这就是 CyclicBarrier 的 javadoc 所说的。

2)我不同意在捕获到 InterruptedException 时清除中断标志

于 2014-01-19T06:16:32.130 回答