简体   繁体   English

线程中断标志语义

[英]thread interrupted flag semantics

I'm having a bit of trouble understanding the semantics for Java's thread interrupted flag. 我在理解Java的线程中断标志的语义方面遇到了一些麻烦。 My understanding is that the flag should only be true after a thread is interrupted, and once set to true will not be false again until the InterruptedException or equivalent has been caught or the flag is explicitly cleared with .interrupted() . 我的理解是,只有在线程被中断后该标志才应该为true,并且一旦设置为true将不会再次为假,直到已捕获InterruptedException或等效或使用.interrupted()显式清除该标志。 Hence, I am not able to explain why the following program prints false : 因此,我无法解释为什么以下程序打印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());
        }
    }
};

(Some details excluded for simplicity - assume it's ok for run() to throw exceptions.) (为简单起见,排除了一些细节 - 假设run()可以抛出异常。)

1) Open CyclicBarrier source and you will see that await() method resets interrupt flag by calling Thread.currentThread().interrupt(). 1)打开CyclicBarrier源,您将看到await()方法通过调用Thread.currentThread()。interrupt()来重置中断标志。 See doWait() which is the actual impl of wait(). 请参阅doWait(),它是wait()的实际impl。 Actually this is what CyclicBarrier's javadoc says. 实际上这就是CyclicBarrier的javadoc所说的。

2) I don't agree that interrupt flag is cleared when InterruptedException has been caught 2)我不同意在捕获InterruptedException时清除中断标志

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM