Thread Interrupt Example in Java

Thread class provides method interrupt() using which one can Interrupt thread.

Before moving ahead, It's important to understand following scenarios :
  • If Thread is blocked in invocation of method like sleep(),join() or Object.wait then It's interrupted status will be cleared and InterruptedException will be thrown.
  • If Thread is blocked in IO Operation upon java.nio.channels.InterruptibleChannel then channel will be closed and interrupted status will be set. Here, Thread will receive ClosedByInterruptException
  • If Thread is blocked in java.nio.channels.Selector then interrupted status will be set and it will return from selection operation.
  • If none of condition mentioned above happens then thread interrupted status will be set.

You can check that Thread is interrupted or not using Thread.isInterrupted()

package com.anuj.threading;

/**
 * ThreadInterruptExample
 * @author Anuj
 *
 */
public class ThreadInterruptExample {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  Thread t1 = new Thread(new Runnable() {
   
   @Override
   public void run() {
    try{
     Thread.currentThread().sleep(100);
    }
    catch(InterruptedException ie){
     System.out.println("Thread Interrupted");
     ie.printStackTrace();
    }
    catch(Exception e){
     e.printStackTrace();
    }    
   }
  });
  
  t1.start();
  t1.interrupt();  
 }
}

Output :
Thread Interrupted
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.anuj.threading.ThreadInterruptExample$1.run(ThreadInterruptExample.java:21)
at java.lang.Thread.run(Thread.java:722)

No comments:

Post a Comment