Wednesday, September 18, 2013

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() {
   public void run() {
    catch(InterruptedException ie){
     System.out.println("Thread Interrupted");
    catch(Exception e){

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

Author : Anuj Patel
Blog :

No comments:

Post a Comment