Thread interruption in Java is a cooperative signaling mechanism — calling interrupt() on a thread doesn't forcibly stop it, it just sets a flag (and wakes it if blocked) that well-behaved code is expected to check and respond to by cleaning up and terminating.
Key Points: • Thread.currentThread().isInterrupted() checks the flag without clearing it; the static Thread.interrupted() checks and clears it in one call. • Blocking methods like Thread.sleep(), Object.wait(), and many java.util.concurrent APIs throw InterruptedException immediately when interrupted, clearing the flag in the process. • When catching InterruptedException, either handle it and stop the task, or re-set the interrupt flag with Thread.currentThread().interrupt() so calling code further up isn't left unaware of the interruption. • Swallowing InterruptedException silently (an empty catch block) is a common bug, since it hides the interruption from the rest of the call stack. • Long-running loops should periodically check the interrupted status so they can exit promptly rather than running to completion regardless of the interrupt request.
Example: A worker thread running a loop should check while (!Thread.currentThread().isInterrupted()) { ... } each iteration, and if it calls a blocking method that throws InterruptedException, it should catch it, perform any needed cleanup, and either return or re-interrupt itself before exiting.
Code Example:
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
doWork();
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // preserve interrupt status
break;
}
}
}Interview Tip: A concise interview answer is:
"Interruption is cooperative — calling interrupt() just sets a flag or wakes a blocked thread, it doesn't force it to stop. Code has to check isInterrupted() periodically, or handle InterruptedException from blocking calls, clean up, and either exit or re-set the interrupt flag so the signal isn't silently lost."