Java Reference
In-Depth Information
14.8. Ending Thread Execution
A thread that has been started becomes alive and the isAlive method will
return TRue for that thread. A thread continues to be alive until it termin-
ates, which can occur in one of three ways:
The run method returns normally.
The run method completes abruptly.
The application terminates.
Having run return is the normal way for a thread to terminate. Every
thread performs a task and when that task is over the thread should go
away. If something goes wrong, however, and an exception occurs that
is not caught, then that will also terminate the threadwe look at this fur-
ther in Section 14.12 on page 379 . By the time a thread terminates it will
not hold any locks, because all synchronized code must have been exited
by the time run has completed.
A thread can also be terminated when its application terminates, which
you'll learn about in " Ending Application Execution " on page 369 .
14.8.1. Cancelling a Thread
There are often occasions when you create a thread to perform some
work and then need to cancel that work before it is completethe most
obvious example being a user clicking a cancel button in a user interface.
To 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 termin-
ate. 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
 
Search WWH ::




Custom Search