-
Notifications
You must be signed in to change notification settings - Fork 4
Java InterruptedException Example
Ramesh Fadatare edited this page Jul 12, 2019
·
2 revisions
This example demonstrates the usage of InterruptedException class with an 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.
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)