This example demonstrates the usage of InterruptedException class and when does this exception occur with a simple example.
The java.lang.InterruptedException thrown when a thread is waiting, sleeping or otherwise occupied, and the thread is interrupted, either before or during the activity. Occasionally a method may wish to test whether the current thread has been interrupted and if so, to immediately throw this exception.
Java InterruptedException Example
In the below example, note that thread interrupted in main() method throws InterruptedException exception that is handled in the run() method.
package com.javaguides.corejava;
class ChildThread extends Thread {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.err.println("InterruptedException caught!");
e.printStackTrace();
}
}
}
public class InterruptedExceptionExample {
public static void main(String[] args) throws InterruptedException {
ChildThread childThread = new ChildThread();
childThread.start();
childThread.interrupt();
}
}
Output:
InterruptedException caught!
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.javaguides.corejava.ChildThread.run(InterruptedExceptionExample.java:7)
Reference
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course