The Life Cycle of a Thread
So far, we have a simple knowledge
of working with threads: we know how to use the
start()
method to start a thread, and how to
terminate a thread by arranging for its run()
method to complete. We’ll now look at two techniques that
provide us more information about the thread during its life cycle.
The isAlive() Method
There is a period of time after you call
the start()
method before the virtual machine
can actually start the thread. Similarly, when a thread returns from
its run()
method, there is a period of time
before the virtual machine can clean up after the thread; and if you
use the stop()
method, there is an even greater
period of time before the virtual machine can clean up after the
thread.
This delay occurs because it takes time to start or terminate a
thread; therefore, there is a transitional period from when a thread
is running to when a thread is not running, as shown in Figure 2.3. After the run()
method
returns, there is a short period of time before the thread stops. If
we want to know if the start()
method of the
thread has been called—or, more usefully, if the thread has
terminated—we must use the isAlive()
method. This method is used to find out if a thread has actually been
started and has not yet terminated:
- boolean isAlive()
Determines if a thread is considered alive. By definition, a thread is considered alive from sometime before a thread is actually started to sometime after a thread is actually stopped.
Figure 2-3. Graphical ...
Get Java Threads, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.