java - 调用 thread.isInterrupted 并打印结果时的不同行为

标签 java multithreading interrupted-exception

我对下面程序中 thread.isInterrupted 的行为有点困惑。

public class ThreadPractice {

    public static void main(String args[]) throws InterruptedException {

        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("Starting thread..." + Thread.currentThread().getName());
                    Thread.sleep(10000);
                    System.out.println("Waking up");
                }catch(InterruptedException e){
                    System.out.println("Thread is interrupted!!!");
                    Thread.currentThread().interrupt();
                }
            }
        });

        t.start();
        Thread.sleep(2000);
        t.interrupt();
        //System.out.println(!t.isInterrupted());
        while(!t.isInterrupted()){
            System.out.println("Current thread not interrupted!!!");
        } 
    }
}

当执行上面的程序时,它打印,

Starting thread...Thread-0
Thread is interrupted!!!

但是当我取消注释 System.out 语句以打印中断状态时,它会进入无限循环打印“当前线程未中断”

我无法弄清楚 System.out 语句到底有什么不同。

最佳答案

请注意,我并不总是遇到无限循环。

我怀疑这是由于操作交错造成的。它还有助于检查线程是否存活:

System.out.println("Current thread not interrupted!!! Alive? " + t.isAlive());

如果线程不活动,则其中断状态为 false。

我得到如下输出:

Starting thread...Thread-0
Thread is interrupted!!!
Current thread not interrupted!!! Alive? true
Current thread not interrupted!!! Alive? false
[infinite loop]

我猜第一个循环看到线程没有被中断,因为 InterruptedException 已经删除了标志 - 然后你在 run 中用 interrupt() 重置标志() 方法和线程可以完成并且不再存在。
下一个循环检查发现它不存在,于是你开始了一个无限循环。


一个有趣的变化可以通过添加:

System.out.println("Exiting Thread!!!");

run() 方法的末尾 - 它提供了足够长的延迟,以便在重置中断标志和线程结束之间检查循环条件。

关于java - 调用 thread.isInterrupted 并打印结果时的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27490381/

相关文章:

java - 使用 WebAppCreator 制作的 GWT Maven 项目在开发模式下不工作

.net - 做跨线程 Winforms 的最简单方法是什么?

使用有限线程的 Java 并发

java - 中断异常 e

java - DataInputStream不读取小文件

java - 在类中设置 "this"

c - 是否可以在 Android 中使用 sched_setaffinity 设置亲和性?

java - 停止无限期运行的线程

java - 如何在 JButton ActionListener 中调用需要 InterruptedException 的方法

java - 如何让 JLabel 显示已选择哪个按钮