O'Reilly logo

Java Threads, Second Edition by Henry Wong, Scott Oaks

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required