【问题标题】:Different behaviour when calling thread.isInterrupted and printing the result调用 thread.isInterrupted 并打印结果时的不同行为
【发布时间】:2015-02-13 22:09:11
【问题描述】:

我对下面程序中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 语句的确切区别。

【问题讨论】:

    标签: java multithreading interrupted-exception


    【解决方案1】:

    请注意,我并不总是陷入无限循环。

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

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

    如果线程不活跃,则其中断状态为假。

    我得到如下输出:

    开始线程...Thread-0
    线程中断!!!
    当前线程没有中断!!!活?真的
    当前线程没有中断!!!活?假
    [无限循环]

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


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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-09
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多