When some other thread calls Thread.interrupt() the method sets Thread's interrupt status flag (initially false) to true. If the Thread is in blocking method like Thread.sleep(), Thread.join() or Object.wait() it unblocks and throws an InterruptedException.
Thread.interrupted() is a static method which can be use to check the current value of interrupt status flag, true or false. It also clears the interrupt status , setting the flag to false. That is calling it twice in a row may likely return false the second time even if it returned true the first time (unless the thread were interrupted again, setting the interrupt status flag to true after the first call)
Note a third method Thread.isInterrupted() which can check the interrupt status without resetting.
Typical use cases:
- Break exceptionally from a blocking operation
- Determine if it is desired to continue a long sequence of instructions at some logical save/stop point
- Determine if it is desired to continue a sequence of instructions prior to beginning a long running task
- Stop executing an iterative process that would otherwise continue into perpetuity (
while(true)
is bad, while(!Thread.interrupted())
is better)