【问题标题】:thread interrupted flag semantics线程中断标志语义
【发布时间】:2014-01-19 06:08:49
【问题描述】:

我在理解 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() 可以抛出异常。)

【问题讨论】:

    标签: java concurrency interrupted-exception


    【解决方案1】:

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

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

    【讨论】:

    • 无需检查 CyclicBarrier 源,因为 CyclicBarrier.await 的 Javadoc 解释了这种行为:“如果当前线程 [...] 在等待时被中断,则抛出 InterruptedException 并且当前线程被中断状态已清除。”
    猜你喜欢
    • 1970-01-01
    • 2011-05-14
    • 1970-01-01
    • 2011-10-03
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多