
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How a Thread Can Interrupt Another Thread in Java
The ‘interrupt’ function can be used in Java to interrupt the execution of a thread with the help of the exception InterruptedException.
The below example shows how the currently executing thread stops execution (because of a new exception raised in the catch block) once it is interrupted −
Example
public class Demo extends Thread { public void run() { try { Thread.sleep(150); System.out.println("In the 'run' function inside try block"); } catch (InterruptedException e) { throw new RuntimeException("The thread has been interrupted"); } } public static void main(String args[]) { Demo my_inst = new Demo(); System.out.println("An instance of the Demo class has been created"); my_inst.start(); try { my_inst.interrupt(); } catch (Exception e) { System.out.println("The exception has been handled"); } } }
Output
An instance of the Demo class has been created Exception in thread "Thread-0" java.lang.RuntimeException: The thread has been interrupted at Demo.run(Demo.java:12)
A class named Demo extends the Thread class. Here, inside the ‘try’ block, a function named ‘run’ is defined that makes the function sleep for 150 milliseconds. In the ‘catch’ block, the exception is caught and relevant message is displayed on the console.
In the main function, an instance of the Demo class is created, and the thread is started using the ‘start’ function. Inside the ‘try’ block, the instance is interrupted, and in the ‘catch’ block, relevant message indicating the exception is printed.