Skip to main content
Threads · Topic 4 of 7

Interrupting a thread

Definition​

You cannot safely force a thread to stop. Instead you ask it to stop by calling interrupt(). The thread checks isInterrupted() (or catches InterruptedException from sleep or wait) and ends itself cleanly.

Example code​

Asking a worker to stop

class Demo {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) { // keep working until asked to stop
// ... do a small piece of work ...
}
System.out.println("worker saw the stop request and is finishing");
});

worker.start();
Thread.sleep(100);
worker.interrupt(); // the polite request
worker.join();
System.out.println("worker finished: " + !worker.isAlive());
}
}

// Output:
// worker saw the stop request and is finishing
// worker finished: true

Finished this page? Track your progress (saved only in your browser).