线程无法捕获InterruptionException

时间:2013-12-27 10:21:03

标签: java multithreading concurrency

我已阅读第146页的Java Concurrency in Practice,我编写了:

class RethroableTask implements Runnable{
    private static final ScheduledExecutorService cancelExec =
            Executors.newScheduledThreadPool(1);
   private Throwable t;
   public void run(){
       try{
            while(true){}
      }catch(Throwable t){
            this.t = t;
       }
   }

  public static void main(String[] args){
          RethroableTask task = new RethrowableTask();
          final Thread taskThread = new Thread(task);
          taskThread.start();
          cancelExec.schedule(new Runnable(){
              public void run(){
                taskThread.interrupt();//i want taskThread can catch interruptedException
      }
     },1,TimeUnit.SECONDS);

    }
}

我希望taskThread抓住InterruptedException作为Throwable,而taskThread isInterrupted真的是true,但是taskThread永远不会抓住它。为什么呢?

我用while(true){}替换

  try{
     Thread.currentThread().sleep(1000);//a blocking method
     }catch(InterruptedException e){
      System.out.println("interruptedException");
     Thread.currentThread().interrupt();
  }

它进来了

2 个答案:

答案 0 :(得分:1)

仅在线程在中断时等待阻塞方法调用时抛出InterruptedException

在所有其他情况下,线程必须检查自己的中断状态。如果您想测试您编写的类,请在while循环中调用阻塞方法。

答案 1 :(得分:1)

停止不同,中断是一种合作机制:在检查中断后,某些代码必须显式抛出InterruptedException当前线程的标志。这可以是声明抛出InterruptedException的JDK方法,例如Thread.sleep,也可以是您自己的代码。

使用

代替空循环
while (true) Thread.sleep(Integer.MAX_VALUE);

这将同时解决两个问题:

  1. 它不会占用CPU;
  2. 在中断时会抛出InterruptedException
相关问题