Saturday 1 March 2014

Thread Interrupt : interrupt()

How to interrupt a Thread
You can interrupt a thread using interrupt() of Thread API.

Syntax
public void interrupt()

Notable points related to interrupt() method
1. When you interrupt a thread which is sleeping, then the sleep throws InterruptedException

Example
class MyThread implements Runnable{
 public void run(){
  try{
   System.out.println("I am so tired, going to sleep");
   Thread.currentThread().sleep(5000);
   System.out.println("Time to work");
  }
  catch(InterruptedException e){
   System.out.println("Somebody interrupted me");
  }
 }

 public static void main(String args[]){
  MyThread task = new MyThread();
  Thread t1 = new Thread(task);
  t1.start();
  t1.interrupt();
 }
}

Output
I am so tired, going to sleep
Somebody interrupted me
  
2. Nothing will happen if you interrupt the thread before calling start() method of the thread.

Example
class MyThread implements Runnable{
 public void run(){
  try{
   System.out.println("I am so tired, going to sleep");
   Thread.currentThread().sleep(5000);
   System.out.println("Time to work");
  }
  catch(InterruptedException e){
   System.out.println("Somebody interrupted me");
  }
 }

 public static void main(String args[]){
  MyThread task = new MyThread();
  Thread t1 = new Thread(task);
  t1.interrupt();
  t1.start();
 }
}
   
Output
I am so tired, going to sleep
Time to work

3. If the thread has pending interrupt, and if it calls the sleep() with pending interrupts, then sleep throws an InterruptedException

class MyThread {
 public static void main(String args[]){
  Thread.currentThread().interrupt();
  try{
   Thread.currentThread().sleep(100);
  }
  catch(InterruptedException e){
   System.out.println("Somebody interrupted me");
  }
 }
}
    
Output
Somebody interrupted me
    



Thread sleep                                                 interrupted status of thread                                                 Home

No comments:

Post a Comment