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

Kum*_*r V 12 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!!!");
        } 
    }
}
Run Code Online (Sandbox Code Playgroud)

当执行上述程序时,它打印,

Starting thread...Thread-0
Thread is interrupted!!!
Run Code Online (Sandbox Code Playgroud)

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

我无法弄清楚System.out语句的确切区别.

ass*_*ias 5

请注意,我并不总是得到无限循环.

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

System.out.println("Current thread not interrupted!!! Alive? " + t.isAlive());
Run Code Online (Sandbox Code Playgroud)

如果线程未处于活动状态,则其中断状态为false.

我得到一个输出:

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

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


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

System.out.println("Exiting Thread!!!");
Run Code Online (Sandbox Code Playgroud)

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