为什么在调用Thread.currentThread().interrupt()后,thread.isInterrupted()返回false?

3
当我运行这个测试时,为什么sleepThread.isInterrupted()总是返回false?(在捕获InterruptedException时,我必须执行Thread.currentThread().interrupt()来设置中断标志。)
@Test
public void t() {
    Thread sleepThread = new Thread() {
        @Override
        public void run() {
            try {
                Thread.sleep(5 * 1000);
            } catch (InterruptedException e) {
                System.out.println("have been interruptted....");
                e.printStackTrace();

                Thread.currentThread().interrupt();

                // in here this.isInterrupted() will return true
                System.out.println("now , instant interrupt flag : " 
                + this.isInterrupted());
            }
        }
    };
    sleepThread.start();

    try {
        sleepThread.interrupt();
        Thread.sleep(2 * 1000);

        // in here ,why sleepThread.isInterrupted() return false ?
        System.out.println("sleep thread interrupt flag : " 
        + sleepThread.isInterrupted());
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

这是输出结果:
have been interruptted
now , instant interrupt flag : true
java.lang.InterruptedException: sleep interrupted
   at java.lang.Thread.sleep(Native Method)
   at com.roundwith.concurrent.Interrupt_Test$1.run(Interrupt_Test.java:15)
sleep thread interrupt flag : false

这里有一个类似的问题没有解决:Thread.isInterrupted总是返回false - Amy Microgoo
侧边栏:这似乎是一种不明智的使用中断的方式。您想要什么样的行为,为什么需要它? - Snild Dolkow
2个回答

0

这是因为在到达最后一个语句时

System.out.println("sleep thread interrupt flag : " + sleepThread.isInterrupted());

线程将会死亡。

尝试在主线程中删除2秒的休眠,您将看到差异(尝试多次运行 - 它仍然可能打印false,但至少主线程有机会看到其他线程是活着的)。


可能会看到差异。但是仍然不能保证在“主”线程在死亡之前有时间看到睡眠线程。 - Snild Dolkow

0
尝试进行更改,
Thread.sleep(2 * 1000);

//Thread.sleep(2 * 1000);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接