Wednesday, October 22, 2014

How to Join Threads in Java

In some situations, we will have to wait for the finalization of a thread. For example, we may have a program that will begin initializing the resources it needs before proceeding with the rest of the execution. We can run the initialization tasks as threads and wait for its finalization before continuing with the rest of the program. For this purpose, we can use the join() method of the Thread class. When we call this method using a thread object, it suspends the execution of the calling thread until the object called finishes its execution. In this article, we are going to explore Join method of thread class.



I will Join You in Heaven
I can rephrase this section heading as "I will wait until you die." That’s right. A thread can wait for another thread to die (or terminate).
Suppose there are two threads, t1 and t2. If the thread t1 executes t2.join(), thread t1 starts waiting until thread t2 is terminated. In other words, the call t2.join() blocks until t2 terminates. Using the join() method in a program is useful if one of the threads cannot proceed until another thread has finished executing.

An example where you want to print a message on the standard output when the program has finished executing. The message to print is "Printing Done."
Output:
Printing Done
Counter = 0
Counter = 1
Counter = 2
Counter = 3
Counter = 4


In the main() method, a thread is created and started. The thread prints integers from 0 to 4. It sleeps for 3 second after printing an integer. In the end, the main() method prints a message. It seems that this program should print the numbers from 0 to 4, followed by your last message. However, if you look at the output, it is in the reverse order. What is wrong with this program?

The JVM starts a new thread called main that is responsible for executing the main() method of the class that you run. In your case, the main() method of the JoinWrong class is executed by the main thread
When the t1.start() method call returns, you have one more thread running in your program (thread t1) in addition to the main thread. The t1 thread is responsible for printing the integers from 0 to 4, whereas the main thread is responsible for printing the message "Printing Done." Since there are two threads responsible for two different tasks, it is not guaranteed which task will finish first. What is the solution? You must make your main thread wait on the thread t1 to terminate. This can be achieved by calling the t1.join() method inside the main() method.


Following example using the t1.join() method call, before printing the final message. When the main thread executes the join() method call, it waits until the t1 thread is terminated. The join() method of the Thread class throws a java.lang.InterruptedException, and your code should be ready to handle it.
Output:
Counter = 0
Counter = 1
Counter = 2
Counter = 3
Counter = 4
Printing Done


Java provides two additional forms of the join() method:

  • join (long milliseconds)
  • join (long milliseconds, long nanos)

In the first version of the join() method, instead of waiting indefinitely for the finalization of the thread called, the calling thread waits for the milliseconds specified as a parameter of the method. .
For example, if the object thread1 has the code, thread2.join(1000) , the thread thread1 suspends its execution until one of these two conditions is true:

  • thread2 finishes its execution
  • 1000 milliseconds have been passed
When one of these two conditions is true, the join() method returns. The second version of the join() method is similar to the first one, but receives the number of milliseconds and the number of nanoseconds as parameters.


Can a thread join multiple threads? The answer is yes. A thread can join multiple threads like so:
t1.join(); // Join t1
t2.join(); // Join t2
t3.join(); // Join t3

You should call the join() method of a thread after it has been started. If you call the join() method on a thread that has not been started, it returns immediately. Similarly, if you invoke the join() method on a thread that is already terminated, it returns immediately.


This example will explain the use where multiple thread call the join method. In this example, we simulate reading of configuration such as network and data source loading before starting out main application.

Output:
Beginning data source loading at : Wed Oct 22 12:14:57 IST 2014
Beginning Network connection loading at : Wed Oct 22 12:14:57 IST 2014
Beginning data source loading finished at : Wed Oct 22 12:15:01 IST 2014
Beginning Network connection finished at : Wed Oct 22 12:15:03 IST 2014
Configuration has loaded

How it works...
When you run this program, you can see how both Thread objects start their execution. First, the DataSourcesLoader thread finishes its execution. Then, the NetworkConnectionsLoader class finishes its execution and, at that moment, the main Thread object continues its execution and writes the final message.




If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

1 comment:

  1. I am technology Enthusiast. Your blog is really awesome, attractive and impressive. I like the way you think. it is very useful for Java SE & Java EE Learners. Your article adds best knowledge to our Java Online Training in India. or learn thru Java Online Training in India Students. or learn thru JavaScript Online Training in India. Appreciating the persistence you put into your blog and detailed information you provide. Kindly keep blogging.

    ReplyDelete