make a thread cancellable takes a bit of work on the programmer's part, but it is a clean and safe mechanism
for getting a thread to terminate. You request cancellation by interrupting the thread and by writing the thread
such that it watches for, and responds to, being interrupted. For example:
Thread 1
Thread 2
Interrupting the thread advises it that you want it to pay attention, usually to get it to halt execution. An
interrupt does not force the thread to halt, although it will interrupt the slumber of a sleeping or waiting
thread.
Interruption is also useful when you want to give the running thread some control over when it will handle an
event. For example, a display update loop might need to access some database information using a transaction
and would prefer to handle a user's "cancel" after waiting until that transaction completes normally. The
user-interface thread might implement a "Cancel" button by interrupting the display thread to give the display
thread that control. This approach will work well as long as the display thread is well behaved and checks at
the end of every transaction to see whether it has been interrupted, halting if it has.
The following methods relate to interrupting a thread: interrupt, which sends an interrupt to a thread;
isInterrupted, which tests whether a thread has been interrupted; and interrupted, a static
method that tests whether the current thread has been interrupted and then clears the "interrupted" state of the
thread. The interrupted state of a thread can be cleared only by that threadthere is no way to "uninterrupt"
another thread. There is generally little point in querying the interrupted state of another thread, so these
methods tend to be used by the current thread on itself. When a thread detects that it has been interrupted, it
often needs to perform some cleanup before actually responding to the interrupt. That cleanup may involve
actions that could be affected if the thread is left in the inter rupted state, so the thread will test and clear its
interrupted state using interrupted.
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 InterruptedException 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();
}
}