Java SE API

Thread.interrupt()

Request interruption according to the API contract.

Formal Syntax & Structure

java syntaxjava
void interrupt()

Working Example

Example Snippetjava
import java.time.Duration;import java.util.concurrent.*;public class Main {    // Only finite tasks and timed coordination are used in these examples.    static void finish(Thread thread) throws InterruptedException {        try {            if (!thread.join(Duration.ofSeconds(3))) {                thread.interrupt();                if (!thread.join(Duration.ofSeconds(3))) throw new AssertionError("worker did not stop");                throw new AssertionError("worker timed out");            }        } catch (InterruptedException e) {            thread.interrupt();            throw e;        }    }    static void await(CountDownLatch latch) {        try {            if (!latch.await(3, TimeUnit.SECONDS)) throw new AssertionError("latch timed out");        } catch (InterruptedException e) {            Thread.currentThread().interrupt();            throw new AssertionError("unexpected cancellation", e);        }    }    public static void main(String[] args) throws Exception {        CountDownLatch ready = new CountDownLatch(1);        CountDownLatch gate = new CountDownLatch(1);        Thread worker = new Thread(() -> {            ready.countDown();            try {                if (!gate.await(3, TimeUnit.SECONDS)) throw new AssertionError("cancel timed out");                throw new AssertionError("unexpected release");            } catch (InterruptedException e) {                System.out.println("cleared: " + !Thread.currentThread().isInterrupted());                Thread.currentThread().interrupt();                System.out.println("restored: " + Thread.currentThread().isInterrupted());            }        });        worker.start();        try { await(ready); } finally { worker.interrupt(); finish(worker); }        System.out.println("terminated: " + !worker.isAlive());    }}
Java Reference