Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Determining Thread Alive Status

After Thread's start() method has been called, a certain period of time elapses before run() is called. That time is used for thread initialization. Also, after run() returns, a certain period of time elapses before the JVM cleans up after the thread. A thread is considered to be alive just before run() is called, and continues to be alive until just after run() returns. Thread's isAlive() method returns true during that interval. Otherwise, false returns.

Why would you want to call isAlive()? You can use that method to determine whether a thread has stopped. For example, suppose a thread, whose object is referenced by th, is running. Now, suppose that another thread x wants to make sure that the thread is finished, so that x can access information produced by the other thread. The following code fragment shows how x (the current thread, in that case) might wait for the other thread to terminate:

while (th.isAlive ())
  try
  {
   Thread.sleep (100);
  }
  catch (InterruptedException e)
  {
  }

th = null;

The code fragment uses a While loop statement to keep checking whether the thread, whose object is referenced by th, is alive. Rather than unnecessarily tie up the processor with repeated checking, the thread regularly puts itself to sleep for 100-millisecond periods.

  • + Share This
  • 🔖 Save To Your Account