2015-08-24 57 views
2

当我运行这个测试时,为什么sleepThread.isInterrupted()总是返回false?为什么在我调用Thread.currentThread()之后thread.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(); 
    } 
} 

这是输出:因为达到

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

线程的最后一条语句会死的时候

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 
+0

这里类似的问题没有解决:[Thread.isInterrupted始终返回false](http://stackoverflow.com/questions/20677604/thread-isinterrupted-always-returns-false) –

+0

边栏:这看起来像是一个不明智的方式来使用中断。你以后有什么样的行为,为什么你需要它? –

回答

0

它。

尝试去除主线程中2秒钟的睡眠并且您会看到不同(尝试几次运行 - 它可能仍会打印错误,但至少主线程有机会看到其他线程还活着)。

+0

你*可能*看到不同之处。仍然不能保证这里的“主”线程在死亡之前有时间看到睡眠线程。 –

+0

@SnildDolkow当然。为清晰起见进行编辑。 – manouti

0

尝试改变,

Thread.sleep(2 * 1000); 

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