12

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说法。

4

1 回答 1

5

请注意,我并不总是得到一个无限循环。

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

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

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

我得到如下输出:

启动线程...Thread-0
线程被中断!!!
当前线程没有中断!!!活?true
当前线程没有中断!!!活?false
[无限循环]

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


通过添加以下内容可以获得一个有趣的变化:

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

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

于 2014-12-15T18:27:26.040 回答