Java Thread interrupt() method

In this tutorial, we will learn about a java.lang.Thread interrupt method with the working examples, use cases of it and importance of the interrupt method.

Thread interrupt() method

interrupt() is a method from java.lang.Thread class and helps to overcome the problem of indefinite wait period of getting monitor locks, avoid deadlocks among threads.

java.lang.Thread interrupt method interrupts a waiting thread for a resource or a sleeping thread or a timed waiting thread or a blocked thread. When interrupt method invoked on a Thread class Object which interrupts its waiting and causes an InterruptedException, due to this reason all the methods which will wait for a resource or sleeping should handle this InterruptedException otherwise compilation will not be successful.

In case if the Thread is not waiting for something still interrupt method is invoked it will not have any effect except interrupted variable of boolean type of a Thread Class object gets changed to true from false.

Thread interrupt() method example

CopiedCopy Code
import java.util.Date;
public class ThreadInterruptExample extends Thread {
	public static void main(String[] args) {
		Thread thread=new ThreadInterruptExample();
		thread.start();
		thread.interrupt();
	}
	public void run()
	{
		System.out.println("Thread going for a sleep for 10s at : "+new Date());
		try {
			sleep(10000L);//sleeping for 10seconds
		} catch (InterruptedException e) {
			System.out.println("Thread interrupted before 10seconds");
		}
		System.out.println("Thread After an interrupt : "+new Date());
	}
}

Output :

Thread going for a sleep for 10s at : Wed Apr 12 18:09:35 IST 2023
Thread interrupted before 10seconds
Thread After an interrupt : Wed Apr 12 18:09:35 IST 2023

Explanation:

We created a new thread and overridden run method, and invoked a sleep for 10s and called interrupt method from main thread. Due to interrupt method invocation sleep got interrupted before 10s and caused an InterruptedException which is handled and printed a line and completed its execution.

Benefits of interrupt method:

  1. Avoids threads going for an indefinite waiting period for a resource.
  2. Helps to avoid a famous deadlock situation.
  3. With proper logging developer can understands where thread starvation is happening.

Conclusion

We learned about the java.lang.Thread interrupt() method by examining its use cases, benefits of using it over a multithreaded environment. Learned how to implement with working example.