isAlive() And join() Methods in Java

In your application you may have a scenario where you spawn a bunch of threads to execute some logic and you want to start any further processing only after all the threads have finished the execution. Which means you need some way to know whether a thread is terminated or not. For that purpose Thread class provides isAlive() and join() methods in Java to check if a thread has finished executing or not.

isAlive() method in Java

This method tests if this thread is alive. A thread is alive if it has been started and has not yet died. Method returns true if thread is alive otherwise it returns false.

isAlive() method syntax

join() method in Java

This method waits until the thread on which it is called terminates. There are three overloaded versions of join() method in Java Thread class.

  • public final void join() throws InterruptedException– Waits indefinitely for this thread to die.
  • public final void join(long millis) throws InterruptedException– Waits at most the time in milliseconds for this thread to die.
  • public final void join(long millis, int nanos) throws InterruptedException– Waits at most the time in milliseconds plus additional time in nanoseconds for this thread to die.

isAlive() and join() method Java example

Here is an example where five threads are created and you want to ensure that any further processing is done only after all these five threads finish executing the run() method and all these five threads are terminated.

First we’ll see what happens if join() method is not used.

Output

As you can see from the output “Now start further processing” message is printed even before the threads started executing. But that is not what you want so let’s see how join() method can help in this scenario.

Output

As you can see “Now start further processing” message is now displayed only after all the five threads have finished executing. With isAlive() methods after the join() methods it can be verified that the threads are terminated.

That’s all for the topic isAlive() And join() Methods in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

One Comment

  1. UshaK, thanks so much for the post.Really thank you! Keep writing.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.