CKTIS / Java
Thread.interrupt — requesting interruption and restoring the status
An interrupt is a signal, not a forced stop. Learn when `InterruptedException` means the interrupt status was cleared and how to restore it.
Version: Java SE 21
Syntax
public void interrupt()
target.interrupt();
Thread.currentThread().interrupt();In Java SE 21, Thread.interrupt is a no-argument instance method of java.lang.Thread that returns void. Calling target.interrupt() signals the thread represented by target, which can be the calling thread itself. Interruption is cooperative: a computation loop can check the status and stop its own work. Interrupting a thread that has not started or has already terminated need not have any effect. A thread can always interrupt itself; interrupting another thread may throw SecurityException.
In the usual case, interrupt() sets the target thread’s interrupt status. When Thread.sleep(long), Object.wait(), or Thread.join() responds to interruption, it clears the status and throws InterruptedException in the thread performing that operation. Not all blocking operations behave this way: blocked I/O on an InterruptibleChannel closes the channel, sets the status, and throws ClosedByInterruptException; a selection operation on a Selector returns with the status set.
If you are not handling the interruption at this level, propagate InterruptedException when the method signature permits it. If you cannot propagate the checked exception, restore the status with Thread.currentThread().interrupt() and stop the interrupted work, for example by returning. Do not ignore the exception or retry unconditionally: an empty catch can lose the signal.
target.isInterrupted() reads the specified thread’s status without changing it. The static method Thread.interrupted() reads and clears only the current thread’s status. Use isInterrupted() when you want to check without clearing.
Examples
public class InterruptDemo {
public static void main(String[] args) {
Thread current = Thread.currentThread();
current.interrupt();
System.out.println("Before sleep: " + current.isInterrupted());
pause();
System.out.println("After pause: " + current.isInterrupted());
System.out.println("Read and clear: " + Thread.interrupted());
System.out.println("After clear: " + current.isInterrupted());
}
private static void pause() {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
System.out.println("In catch: " + Thread.currentThread().isInterrupted());
Thread.currentThread().interrupt();
return;
}
}
}Result
Before sleep: true In catch: false After pause: true Read and clear: true After clear: false
The main thread interrupts itself before `sleep`. The status is `false` in `catch` and `true` after `pause` returns because the status was restored. `Thread.interrupted()` returns `true` and clears the status, so the last read is `false`.
Related lessons
- Java · Lesson 49 · Intermediate · Version: 2
- Java · Lesson 58 · Intermediate · Version: 2