2010-01-06 61 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或我们的机器的速度有所不同。如果它与国家的清算有关,那可能会解释变数。