java - 线程中断标志语义

标签 java concurrency interrupted-exception

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

最佳答案

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

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

关于java - 线程中断标志语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21213783/

相关文章:

java - 如何将 Android Navigation Architecture fragment 动画化为滑过旧 fragment ?

java - Android WebView 中显示白屏

postgresql - postgresql插入和选择时如何锁表?

java - 线程通过调用interrupt()被中断,但是Thread.isInterrupted()返回false

java - ThreadPoolExecutor.shutdownNow() 没有在 Thread 中抛出 InterruptedException

java - 从 Java 代码调用 Spring Scheduler 执行

java - 覆盖自身的字符串数组列表

java - 无界无等待?

选择更新甚至排序之间的 PostgreSQL 死锁

java - 我应该在抛出异常之前使用 Thread.currentThread.interrupt() 吗?