The Thread.interrupt() Method
You'll learn how to signal a thread to stop what it's doing by calling interrupt() on its reference.
What Is Thread.interrupt()?
The interrupt() method is how one thread can politely request another thread to stop or check its status. When you call interrupt() on a thread reference, Java sets that thread's interruption status flag to true. This is like tapping someone on the shoulder during a task—it doesn't force them to stop, but it sends a clear signal they should check if they need to respond.
How to Call interrupt()
You need a reference to a Thread object. Then simply call:
Thread worker = new Thread(() -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("I was interrupted!");
}
});
worker.start();
// From another thread (like main):
worker.interrupt(); // Sets worker's interrupt flag
When interrupt() executes, two things can happen:
- If the thread is sleeping or waiting: It immediately throws
InterruptedExceptionand clears the flag - If the thread is running normally: The flag is set, but nothing happens until the thread checks it
Why Not Just Force-Stop?
Think of interruption as a cooperative protocol. You're saying "please stop when convenient," not pulling the emergency brake. The interrupted thread decides how to respond, allowing it to clean up resources safely.
Thread task = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
System.out.println(i);
}
});
task.start();
task.interrupt(); // Flag is set, but loop continues unless thread checks
Key Takeaway: Call interrupt() on a thread reference to set its interruption status flag, signaling that thread to stop or take action—the target thread must cooperate by checking the flag or handling InterruptedException.