2010-01-06 27 views
8

下面的程序演示了此問題(最新JVM &諸如此類的東西):Thread.isInterrupted不起作用,Thread.interrupted確實

public static void main(String[] args) throws InterruptedException { 
    // if this is true, both interrupted and isInterrupted work 
    final boolean withPrint = false; 

    // decide whether to use isInterrupted or interrupted. 
    // if this is true, the program never terminates. 
    final boolean useIsInterrupted = true; 

    ExecutorService executor = Executors.newSingleThreadExecutor(); 
    final CountDownLatch latch = new CountDownLatch(1); 
    Callable<Void> callable = new Callable<Void>() { 
     @Override 
     public Void call() throws Exception { 
      Random random = new Random(); 
      while (true) { 
       if (withPrint) { 
        System.out.println(random.nextInt()); 
        System.out.flush(); 
       } 
       if (useIsInterrupted) 
       { 
        if (Thread.currentThread().isInterrupted()) 
         break; 
       } 
       else 
       { 
        if (Thread.interrupted()) 
         break; 
       } 
      } 
      System.out.println("Nice shutdown"); 
      latch.countDown(); 
      return null; 
     } 
    }; 
    System.out.println("Task submitted"); 
    Future<Void> task = executor.submit(callable); 
    Thread.sleep(100); 
    task.cancel(true); 
    latch.await(); 
    System.out.println("Main exited"); 
    executor.shutdown(); 
} 
+0

它不*總是*不能停止。 – Jerome 2010-01-06 10:57:25

+0

在我的機器上它有。 – ripper234 2010-01-06 11:00:29

+0

jerome,檢查你的編譯器設置...也許你正在使用更早的JVM。 – PaulP1975 2010-01-06 12:07:14

回答

4

這看起來像具有多處理器機器一個known issue,主要是在從1.5 64位操作系統和Java版本 - 7.0

的問題的描述: 雖然運行兩個同時線程,所述第一線程中斷第二個使用Thread.interrupt()。 第二個線程測試它是否被中斷調用始終返回false的Thread.isInterrupted()方法。

這發生在運行64位操作系統(Vista和Linux)的多處理器PC上。 在Vista 64位上,當使用64位JVM(所有版本從1.5到1.7)時會發生這種情況,但在使用32位JVM時不會發生。 在Linux 64位上,使用64位JVM(所有版本從1.5到1.7)或使用32位JVM(所有版本從1.5到1.7)時都會發生這種情況。

解決方法是安裝帶修補程序的版本,該修補程序爲1.6.0_16-b02或更高版本。

+0

很好的結果,但是bug的狀態是「在hs16(b04)中解決」。這是我正在運行的版本: Java版本「1.6.0_14」 Java™SE運行時環境(版本1.6.0_14-b08) Java HotSpot™64位服務器VM(版本14.0-b16 ,混合模式) – ripper234 2010-01-06 12:47:53

+0

也許我只是不明白Java版本號。該錯誤是否應該在JDK中修復?我應該重新打開還是下載新的JDK? – ripper234 2010-01-06 12:54:57

+0

hs16(b04)是熱點版本,不是JRE版本。看起來修復版本是1.6.0_16-b02,比你的版本晚,所以你應該下載最新版本(1.6.0_17)。 – Mocky 2010-01-06 13:55:29

0

ripper234,我只是跑我這臺機器上,它總是停不管什麼價值我用於打印和哪些中斷使用。我正在使用jdk1.6.0_16。看着javadoc,也許它與中斷()在每次調用之後清除(中斷)狀態並且isInterrupted()不清除有關。事實上,它有時爲jerome,總是爲我,而從來沒有(?)爲您可以表明我們正在使用的jdks或我們的機器的速度有所不同。如果它與國家的清算有關,那可能會解釋變數。

相關問題