A thread sends an interrupt by invoking
interrupt
on the Thread
object for the thread to be interrupted.
For the interrupt mechanism to work correctly, the interrupted thread
must support its own interruption.
InterruptedException
, it simply
returns from the run
method after it catches that
exception. For example, suppose the central message loop in the
SleepMessages
example were in the run
method
of a thread's Runnable
object. Then it might be modified
as follows to support interrupts:
for (int i = 0; i < importantInfo.length; i++) { //Pause for 4 seconds try { Thread.sleep(4000); } catch (InterruptedException e) { //We've been interrupted: no more messages. return; } //Print a message System.out.println(importantInfo[i]); }
InterruptedException
, such as
sleep
, are designed to cancel their current operation and
return immediately when an interrupt is received.
What if a thread goes a long time without invoking a method that
throws InterruptedException
? Then it must periodically
invoke Thread.interrupted
, which returns
true
if an interrupt has been received. For example:
for (int i = 0; i < inputs.length; i++) { heavyCrunch(inputs[i]); if (Thread.interrupted()) { //We've been interrupted: no more crunching. return; } }
InterruptedException
:
if (Thread.interrupted()) { throw new InterruptedException(); }
catch
clause.
Thread.interrupt
sets this flag. When a thread checks for an interrupt by invoking the
static method Thread.interrupted
, interrupt status is
cleared. The non-static isInterrupted
method, which is
used by one thread to query the interrupt status of another, does not
change the interrupt status flag.
By convention, any method that exits by throwing an
InterruptedException
clears interrupt status when it does
so. However, it's always possible that interrupt status will
immediately be set again, by another thread invoking
interrupt
.