Interrupting a thread

Interrupting a thread

We can interrupt a sleeping or waiting thread by using interrupt method of thread class.

public void interrupt()
class MyThread extends Thread {
   public void run() {
      try {
         for (int i = 0; i < 5; i++) {
            System.out.println("Child Thread :" + i);
            Thread.sleep(2000);
         }
      } catch (InterruptedException e) {
         System.out.println("I got interrupted");
      }
   }
}

public class MyThreadInterrupt {
   public static void main(String[] args) {
      MyThread t = new MyThread();
      t.start();
      t.interrupt(); 
      System.out.println("Main thread");
   }
}

Output

Main thread
Child Thread :0
I got interrupted

Note

  • Whenever we are calling interrupt() method we may not see the effect immediately, if the target Thread is in sleeping or waiting state it will be interrupted immediately.
  • If the target Thread is not in sleeping or waiting state then interrupt call will wait until target Thread will enter into sleeping or waiting state. Once target Thread entered into sleeping or waiting state it will effect immediately.
  • In its lifetime if the target Thread never entered into sleeping or waiting state then there is no impact of interrupt call simply interrupt call will be wasted.

E.g

class MyThread extends Thread {
   public void run() {
      for (int i = 0; i < 5; i++) {
         System.out.println("Child Thread :" + i);
      }
      try {
         Thread.sleep(2000);
      } catch (InterruptedException e) {
         System.out.println("Thread got interrupted");
      }
   }
}

public class MyThreadInterrupt {
   public static void main(String[] args) {
      MyThread t = new MyThread();
      t.start();
      t.interrupt(); 
      System.out.println("Main thread");
   }
}

Output

Main thread
Child Thread :0
Child Thread :1
Child Thread :2
Child Thread :3
Child Thread :4
Thread got interrupted
  • In the above program interrupt() method call invoked by main Thread will wait until child Thread entered into sleeping state.
  • Once child Thread entered into sleeping state then it will be interrupted immediately.
Interrupting a thread


Scroll to top