Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

InterruptedException

A checked exception: a waiting thread was asked to stop.

Available since: Java 1.0

Syntax

public class InterruptedException extends Exception

Examples

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, stopping

Notes

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

In the tutorial

  • Threads — Threads in Java — the Thread class, starting with start, waiting with join, Thread.sleep, thread names and unpredictable execution order.

Thanks for reading!

Donate to the site — we work hard for you.