How to Join Multiple Threads in Java? [Thread.join() Example] (original) (raw)
Join method from the Thread class is an important method and used to impose order on the execution of multiple Threads. The concept of joining multiple threads is very popular in a multithreading interview question. Here is one such question, “You have three threads T1, T2, and T3, How do you ensure that they finish in order T1, T2, T3 ?. This question illustrates the power of the join method on multithreaded programming. Unlike classical thread questions like the difference between the wait and sleep method or solving the producer-consumer problem in Java, This one is a bit tricky.
You can do this by using the join method, by calling T1.join() from T2 and T2.join() from T3. In this case thread, T1 will finish first, followed by T2 and T3. In this Java multithreading tutorial, we will have a closer look at the join method with a simple example.
The idea is to illustrate how the join method works in simple words. By the way from Java 5 onwards you can also use CountDownLatch and CyclicBarrier classes to implement scenarios like one thread is waiting for other threads to finish their task.
Btw, if you are serious about mastering Java multi-threading and concurrency then I also suggest you take a look at the Java Multithreading, Concurrency, and Performance Optimization course by Michael Pogrebinsky on Udemy. It's an advanced course to become an expert in Multithreading, concurrency, and Parallel programming in Java with a strong emphasis on high performance.
When to use the join method in Java?
As I said join is an important and useful method from Thread class but many times overlooked. Similar to the wait for method, by using the join method, we can make one Thread to wait for another.
The primary use of Thread.join() is to wait for another thread and start execution once that Thread has completed execution or died. Join is also a blocking method, which blocks until the thread on which join has called a die or specified waiting time is over.
By the way, understanding, how to join method works, is not straight forward. Many developers get confused about things like, which thread will wait, which thread will join etc. These points will be clearer when we go through an example of joining multiple Thread in Java using join() method.
Thread Join Example in Java
Here is a simple example of joining two threads using the Thread.join() method. By the way, unlike Thread.sleep() method, join() is not a static method, it needs to be called on a java.lang.Thread object. The current thread, which calls the join method will wait until the thread on which join has called a die or wait at most specified millisecond for this thread to die.
/**
* Sample Java class to illustrate How to join two threads in Java.
* join() method allows you to serialize the processing of two threads.
*/
public class Join {
public static void main(String args[]) throws InterruptedException{
System.out.println(Thread.currentThread().getName() + " is Started");
Thread exampleThread = new Thread(){
public void run(){
try {
System.out.println(Thread.currentThread().getName() + " is Started");
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + " is Completed");
} catch (InterruptedException ex) {
Logger.getLogger(Join.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
exampleThread.start();
exampleThread.join();
System.out.println(Thread.currentThread().getName() + " is Completed");
}
}
Output:
main is Started
Thread-0 is Started
Thread-0 is Completed
main is Completed
If you look at the above example, the first main thread is started, and then it creates another thread, whose name is "Thread-0" and started it. Since Thread-0 sleeps for 2 seconds, it requires at least 2 seconds to complete and in between main thread called join method on the Thread-0 object.
Because of the join method, now, the main thread will wait until Thread-0 completes its operation or You can say the main thread will join Thread-0. If you look at the output, it confirms this theory.
If you want to learn more about essential thread concepts like joins, inter-thread communication, locking and object sharing then I highly recommend you to join Multithreading and Parallel Computing in Java course on Udemy. It's a great course on essential thread concept in Java.
Important points on Thread.join method
Now we know How to use the join method in Java, it’s time to see some important points about Thread.join() method.
Join method throws IntrupptedException if another thread interrupted waiting for thread as a result of join() call.
Join is also an overloaded method in Java, three version of join() available, check Javadoc for details.
That’s all on How to join two threads in Java with an example. You can Join multiple threads by using Thread.join() method. Join is particularly useful to make one thread wait for another, or serializing two functions e.g. first load your cache and then start processing the request.
Further Learning
Multithreading and Parallel Computing in Java
Java Concurrency in Practice - The Book
Applying Concurrency and Multi-threading to Common Java Patterns
Java Concurrency in Practice Course by Heinz Kabutz
Related Java multithreading Tutorials from Javarevisited Blog