InterruptedException
A checked exception: a waiting thread was asked to stop.
Available since: Java 1.0
Syntax
public class InterruptedException extends ExceptionExamples
Interrupting a sleeping thread:
void main() throws InterruptedException {
Thread worker = new Thread(() -> {
try {
Thread.sleep(10_000);
IO.println("finished");
} catch (InterruptedException e) {
IO.println("interrupted, stopping");
}
});
worker.start();
Thread.sleep(100);
worker.interrupt();
worker.join();
}Output:
interrupted, stoppingNotes
It is thrown by waiting methods: sleep(), join(), Future.get(), CountDownLatch.await(). An interrupt is a polite request to stop. Do not swallow the exception with an empty catch: either finish the work or restore the flag with Thread.currentThread().interrupt().
See also
- Thread.sleep() — Pauses the current thread for a given time.
- Thread.join() — Waits for a thread to finish.
- Future.get() — Waits for a task to finish and returns its result.
In the tutorial
- Threads — Threads in Java — the Thread class, starting with start, waiting with join, Thread.sleep, thread names and unpredictable execution order.