Java Reference
In-Depth Information
Interrupting a thread will normally not affect what it is doing, but a
few methods, such as
sleep
and
wait
, throw
InterruptedException
. If your
thread is executing one of these methods when it is interrupted, the
method will throw the
InterruptedException
. Such a thrown interruption
clears the interrupted state of the thread, so handling code for
Interrup-
tedException
commonly looks like this:
void tick(int count, long pauseTime) {
try {
for (int i = 0; i < count; i++) {
System.out.println('.');
System.out.flush();
Thread.sleep(pauseTime);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
The
tick
method prints a dot every
pauseTime
milliseconds up to a max-
way to do this. If something interrupts the thread in which
tick
is run-
ning,
sleep
will throw
InterruptedException
. The ticking will then cease,
and the
catch
clause will reinterrupt the thread. You could instead de-
clare that
tick
itself throws
InterruptedException
and simply let the ex-
ception percolate upward, but then every invoker of
tick
would have
to handle the same possibility. Reinterrupting the thread allows
tick
to
clean up its own behavior and then let other code handle the interrupt
as it normally would.
In general any method that performs a blocking operation (either dir-
ectly or indirectly) should allow that blocking operation to be cancelled
with
interrupt
and should throw an appropriate exception if that occurs.
This is what
sleep
and
wait
do. In some systems, blocking I/O operations
will respond to interruption by throwing
InterruptedIOException
(which
is a subclass of the general
IOException
that most I/O methods can