Master java skills

How to interrupt a thread

When a thread is in sleeping or waiting state, calling interrupt() method on that thread, breaks the sleeping or waiting state by throwing InterruptedException. If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal behaviour and doesn’t interrupt the thread but sets the interrupt flag to true. Let’s first see the methods provided by the Thread class for thread interruption.

Following 3 methods of Thread class can be used for working with interruption of threads

  • public void interrupt()
  • public static boolean interrupted()
  • public boolean isInterrupted()

Example

In the below example, we can see how we can interrupt a thread.

package com.javatrainingschool;

public class ThreadInterruptionExample implements Runnable {
  
    public void run(){  
        try{  
            Thread.sleep(2000);  
            System.out.println("task");  
        }catch(InterruptedException e){  
           throw new RuntimeException("Thread interrupted" + e);  
         }
    }  

    public static void main(String args[]){  
        Thread t1 = new Thread(new ThreadInterruptionExample());  
        t1.start();  
        try{  
            t1.interrupt();  
        }catch(Exception e){
             System.out.println("Exception handled "+e);
         }  
    }  
}  
Output :
Exception in thread "Thread-0" java.lang.RuntimeException: Thread interruptedjava.lang.InterruptedException: sleep interrupted
	at com.sks.ThreadInterruptionExample.run(ThreadInterruptionExample.java:10)
	at java.lang.Thread.run(Thread.java:748)

When interrupting thread wakes the thread

In the below example, calling interrupt() method will just interrupt the thread and wake it up so that it can continue working.

package com.javatrainingschool;

public class ThreadInterruptionExample implements Runnable {
  
    public void run(){  
        try{  
            Thread.sleep(2000);  
            System.out.println("task");  
        }catch(InterruptedException e){  
           System.out.println("Thread interrupted. Continue working");  
         }
        System.out.println("Thread continued.");  
    }  

    public static void main(String args[]){  
        Thread t1 = new Thread(new ThreadInterruptionExample());  
        t1.start();  
        try{  
            t1.interrupt();  
        }catch(Exception e){
             System.out.println("Exception handled "+e);
         }  
    }  
}  
Output :
Thread interrupted. Continue working
Thread continued.

Calling interrupt() method when thread is not sleeping

In such a situation, the thread will continue working as it is. However, interrupted flag will be set to true.

package com.javatrainingschool;

public class ThreadInterruptionExample implements Runnable {
  
    public void run(){  
        for(int i=0; i < 50; i++) {
            System.out.println("task");  
        }
    }  

    public static void main(String args[]){  
        Thread t1 = new Thread(new ThreadInterruptionExample());  
        t1.start();  
        try{  
            t1.interrupt();  
        }catch(Exception e){
             System.out.println("Exception handled "+e);
         }  
    }  
}  

It will keep running and print values from 1 to 49.

isInterrupted() and interrupted() methods

  1. isInterrupted() method tells about whether the method has been interrupted or not. It returns true or false depending upon whether it has been interruped or not.
  2. The static interrupted() method returns the value interrupted flag. And after returning, it sets the flag to false if it is true.
package com.sks;

public class ThreadInterruptionExample implements Runnable {

    public void run() {
        for (int i = 1; i <= 2; i++) {
	    if (Thread.interrupted()) {
	        System.out.println(Thread.currentThread().getName() + " : interrupted() method call.");
	    } else {
	        System.out.println(Thread.currentThread().getName() +  " : thread is not interrupted.");
	      }
	}
    }

    public static void main(String args[]) {

	Thread t1 = new Thread(new ThreadInterruptionExample(), "First Thread");
	Thread t2 = new Thread(new ThreadInterruptionExample(), "Second Thread");

	t1.start();
	t1.interrupt();

	t2.start();

    }
}
Output :
Second Thread : thread is not interrupted.
First Thread : interrupted() method call.
First Thread : thread is not interrupted.
Second Thread : thread is not interrupted.