Java : InterruptedException with Examples

InterruptedException (Java SE 21 & JDK 21) with Examples.
You will find code examples on most InterruptedException methods.


Summary

Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity.

Class diagram

Sequence

try (final var executor = Executors.newSingleThreadExecutor()) {

    System.out.println("-- submit --");
    final var future = executor.submit(() -> {
        try {
            System.out.println("sleep ...");
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            System.out.println("InterruptedException!");
        }
    });

    TimeUnit.SECONDS.sleep(1);

    System.out.println("-- interrupt --");
    future.cancel(true);
}

// Result
// ↓
//-- submit --
//sleep ...
//-- interrupt --
//InterruptedException!

Constructors

InterruptedException ()

Constructs an InterruptedException with no detail message.

final var e = new InterruptedException();
System.out.println(e); // java.lang.InterruptedException

InterruptedException (String s)

Constructs an InterruptedException with the specified detail message.

final var e = new InterruptedException("abcd");
System.out.println(e); // java.lang.InterruptedException: abcd

Methods declared in Throwable

addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Please see the link below.


Related posts

To top of page