为什么即使在调用Thread.currentThread()之后thread.isInterrupted()也返回false.interrupt()

时间:2015-08-24 17:49:19

标签: java multithreading

当我运行此测试时,为什么sleepThread.isInterrupted()总是返回false?

(当我赶上Thread.currentThread().interrupt()时,我必须执行InterruptedException来设置中断标志。

@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

2 个答案:

答案 0 :(得分:0)

这是因为到达最后一个陈述时

$ awk '/blah/ {f=NR} f && NR==f+1' a
1
4
7

线程将会死亡。

尝试删除主线程中的2秒睡眠,你会看到差异(尝试几次运行 - 它仍然可以打印错误,但至少主线程有机会看到另一个线程存活)。 / p>

答案 1 :(得分:0)

尝试改变,

Thread.sleep(2 * 1000);

//Thread.sleep(2 * 1000);
相关问题