Interrupting a Thread in Java

Naveen AnamaneniUpdated · 4 min read

Interrupting a thread in Java means asking it to stop what it's doing. Calling t.interrupt() sets a flag inside thread t. If t is sleeping, waiting or joining, that call ends early with InterruptedException. If t is busy computing, nothing happens automatically; the thread must check its flag with isInterrupted() and stop by itself. Interruption is cooperative: the thread decides how to respond. In this lesson, you will learn the interruption methods and how to write tasks that stop cleanly.

Methods

MethodDescription
t.interrupt()It is used to set thread t's interrupted flag (and wake it if it's waiting).
t.isInterrupted()It returns t's flag without changing it.
Thread.interrupted()It returns the current thread's flag and clears it.

Methods such as sleep, join and wait throw InterruptedException when interrupted, and clear the flag when they do.

Example: Stopping a Busy Thread

Let's see an example of a thread that computes in a loop and checks its flag.

BusyStop.java▶ Try it
public class BusyStop {
    public static void main(String[] args) throws InterruptedException {
        Thread counter = new Thread(() -> {
            long count = 0;
            while (!Thread.currentThread().isInterrupted()) {
                count++;
            }
            System.out.println("Counter stopped cleanly after counting: "
                + (count > 0));
        });
 
        counter.start();
        Thread.sleep(200);
        counter.interrupt();
        counter.join();
        System.out.println("Interrupted flag still set? "
            + counter.isInterrupted());
    }
}
Output
Counter stopped cleanly after counting: true
Interrupted flag still set? true

Explanation: The loop keeps running until its own interrupted flag becomes true. interrupt() sets the flag, the loop ends, and the thread prints a message and finishes. Afterwards the thread has terminated, but it keeps its flag: in modern Java, isInterrupted() on a finished thread still reports true if it was interrupted.

Example: Handling InterruptedException Correctly

Restore.java▶ Try it
public class Restore {
    static void pause(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
 
    public static void main(String[] args) throws InterruptedException {
        Thread worker = new Thread(() -> {
            int step = 0;
            while (!Thread.currentThread().isInterrupted()) {
                step++;
                System.out.println("Advitha works on step " + step);
                pause(150);
            }
            System.out.println("Worker saw the interrupt and stopped");
        });
        worker.start();
        Thread.sleep(400);
        worker.interrupt();
        worker.join();
    }
}
Output
Advitha works on step 1
Advitha works on step 2
Advitha works on step 3
Worker saw the interrupt and stopped

Explanation: The interrupt arrives while the worker is sleeping, so sleep throws and clears the flag. The helper pause catches it and calls interrupt() again to restore the flag. The loop condition then sees the flag and stops. Without restoring it, the loop would keep going forever.

Common Mistakes

Swallowing InterruptedException. The thread loses the stop request.

Using Thread.interrupted() to just check. It also clears the flag; use isInterrupted() to read it.

Using the deprecated stop() method. It's removed in modern Java and was unsafe; use interruption.

Interview Corner

How do you stop a thread in Java?

Use cooperative interruption. Call thread.interrupt() to set its interrupted flag. Blocking calls such as sleep, wait and join respond by throwing InterruptedException; code that doesn't block should regularly check Thread.currentThread().isInterrupted() and exit. When catching InterruptedException, either rethrow it or restore the flag with Thread.currentThread().interrupt(). Thread.stop() is unsafe and no longer supported.

Practice

  1. Easy: Interrupt a thread that is waiting in join() on another long-running thread, and print a message from the catch block.
  2. Harder: Write a file-copy task that copies in chunks and checks isInterrupted() between chunks, deleting the partial copy if it's canceled.

Quick check: Interruption

4 questions
1What does t.interrupt() do?
2What does Thread.interrupted() do besides returning the flag?
3What should a catch block for InterruptedException usually do?
4Does interrupt() stop a thread busy computing in a loop?

Key Takeaways

Was this tutorial helpful?

Lesson 394 of 482