Saturday, 1 March 2014

Clear the interrupted status : interrupted()

Tests whether the current thread has been interrupted. The interrupted status of the thread is cleared by this method. In other words, if this method were to be called twice in succession, the second call would return false (unless the current thread were interrupted again, after the first call had cleared its interrupted status and before the second call had examined it).

Syntax
public static boolean interrupted()

returns true if the current thread has been interrupted; false otherwise

interrupted method clears the status of interrupted status flag. Where as isInterrupted() doesn't.

Example
class MyThread implements Runnable{
 public void run(){
  for(int i=0; i <1000000000; i++){
   int k = i+1, j=i;
   k = i/k;
   k = k*i;
  }
  System.out.println("Is thread interrupted " + Thread.currentThread().isInterrupted());
  System.out.println("Is thread interrupted " + Thread.currentThread().isInterrupted());
  System.out.println("Is thread interrupted " + Thread.interrupted());
  System.out.println("Is thread interrupted " + Thread.currentThread().isInterrupted());
 }

 public static void main(String args[]){
  MyThread task1 = new MyThread();
  Thread t1 = new Thread(task1);
  t1.start();
  t1.interrupt();
 }
}
     
Output   
Is thread interrupted true
Is thread interrupted true
Is thread interrupted true
Is thread interrupted false

Notable points
1. Sleep() clears the interrupted flag status, before throwing InterruptedException
class MyThread implements Runnable{
 public void run(){
  try{
   for(int i=0; i <1000000000; i++){
    int k = i+1, j=i;
    k = i/k;
    k = k*i;
   }
   System.out.println("Is thread interrupted " + Thread.currentThread().isInterrupted());
   Thread.currentThread().sleep(1000);
  }
  catch(InterruptedException e){
   System.out.println("Is thread interrupted " + Thread.currentThread().isInterrupted());
  }
 }
 
 public static void main(String args[]){
  MyThread task1 = new MyThread();
  Thread t1 = new Thread(task1);
  t1.start();
  t1.interrupt();
 }
}

 Output
Is thread interrupted true
Is thread interrupted false



Interrupted status of thread                                                 Daemon threads                                                 Home

No comments:

Post a Comment