王奕然
王奕然

Reputation: 4059

Thread can't catch InterruptionException

I have read the Java Concurrency in Practice on page 146, and I have coded the:

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);

    }
}

I want taskThread to catch InterruptedException as Throwable, and really the taskThread isInterrupted is true,but taskThread never catches it. Why?

I substitute while(true){} with

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

it come in catch

Upvotes: 0

Views: 77

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200256

Unlike stopping, interruption is a cooperative mehanism: the InterruptedException must be explicitly thrown by some code after checking the interrupted flag of the current thread. This can be either a JDK method which declares to throw InterruptedException such as Thread.sleep, or your own code.

Instead of your empty loop, use

while (true) Thread.sleep(Integer.MAX_VALUE);

This will solve two problems at once:

  1. it won't hog the CPU;
  2. it will throw an InterruptedException when interrupted.

Upvotes: 1

Duncan Jones
Duncan Jones

Reputation: 69399

An InterruptedException is only thrown when a thread is waiting on a blocking method call at the moment of interruption.

In all other situations, a thread must check its own interrupted status. If you want to test the class you've written, call a blocking method in your while loop.

Upvotes: 1

Related Questions