Class 2 |
Intermediate Java 30-IT-397 |
|
Interrupting Threads
-
When the run() method of a Thread completes, the thread ends naturally.
-
What if you need to end that thread prematurely? You must call
the interrupt() method of that thread to request a termination.
-
Note, this does not actually stop the thread, it simply requests that the
thread stop.
-
Calling interrupt() will lead to two possible outcomes:
-
If the thread is currently running, it will need to check to see if an
interrupt has been requested with the interrupted() method. If so,
it should stop processing.
-
If the thread does not periodically check while running, it will never
know, until it sleeps!
-
It is a good idea to plan this wisely. Check for interrupts after
resources have been closed, variables have been written to a final state,
etc.
-
On the other hand, the thread cannot check for interrupts if it is sleeping
or waiting. If an interrupt is called at this time, an InterruptedException
is called.
-
Thus, you need to wrap the contents of the run() method in a try-catch
block, and handle InterruptedExceptions gracefully. This is a good
time to close resources, bring variables to their final state, etc.
Interrupt Example
Thread States

Created by: Brandan Jones
December 17, 2001