Saturday 1 March 2014

Know the interrupted status of the thread

How to know whether a thread is interrupted or not
Thread API provides a method called, isInterrupted(), which returns true if the thread is interrupted, otherwise returns false.

Syntax
public boolean isInterrupted()

Tests whether this thread has been interrupted. The interrupted status of the thread is unaffected by this method. Returns true if the thread is interrupted otherwise return false.

Example
class MyThread implements Runnable{
 public void run(){
  try{
   Thread.currentThread().sleep(5000);
  }
  catch(Exception e){
   try{
    Thread.currentThread().sleep(5000);
    System.out.println("Somebody interrupted me");
   }
   catch(InterruptedException e1){
   }
  }
 }

 public static void main(String args[]){
  MyThread task1 = new MyThread();
  Thread t1 = new Thread(task1);
  t1.start();
  t1.interrupt();
  System.out.println("Is thread1 interrupted " + t1.isInterrupted());
 }
}

Output   
Is thread1 interrupted true
Somebody interrupted me

Notable points
1. A thread interruption ignored, if a thread was not alive at the time of the interrupt called
i.e., if the thread finishes its execution, and you call the interrupted() after thread finishes its execution, it will returns false.

Example
class MyThread implements Runnable{
 public void run(){
  try{
   Thread.currentThread().sleep(2000);
  }
  catch(Exception e){
   System.out.println("Somebody interrupted me");
  }
 }

 public static void main(String args[]){
  MyThread task1 = new MyThread();
  Thread t1 = new Thread(task1);
  t1.start();
  t1.interrupt();
  
  try{
   Thread.currentThread().sleep(2000);
  }
  catch(Exception e){
  }
  System.out.println("Is thread1 interrupted " + t1.isInterrupted());
 }
}

Output   
Somebody interrupted me
Is thread1 interrupted false

2. If a thread is interrupted before it started, then nothing will happen, so isInterrupted() also return false
class MyThread implements Runnable{
 public void run(){
  try{
   Thread.currentThread().sleep(2000);
  }
  catch(Exception e){
   System.out.println("Somebody interrupted me");
  }
 }

 public static void main(String args[]){
  MyThread task1 = new MyThread();
  Thread t1 = new Thread(task1);
  t1.interrupt();
  System.out.println("Is thread1 interrupted " + t1.isInterrupted());
  t1.start();
  System.out.println("Is thread1 interrupted " + t1.isInterrupted());
 }
}

Output

Is thread1 interrupted false
Is thread1 interrupted false



Interrupt thread                                                 Clear interrupt status                                                 Home

No comments:

Post a Comment