Java Thread join() method

In this tutorial, we will learn about java.lang.Thread join method and the uses cases of it, benefits of join method over sleep method with working examples.

java.lang.Thread join() method

join() is a method from java.lang.Thread class and helps to pause a current thread execution until target thread completes its execution, or allows a current thread to wait up to certain point of time without waiting for complete execution of target thread. In case if target threads complete its execution before specified time, then calling thread will resume its execution will not wait until specified time elapse.

The following three overloaded methods available in Thread class.

  1. join()
  2. join(long millis)
  3. join(long millis,int nanoseconds)

Thread join() method example:

The following are the examples of join() method.

CopiedCopy Code
public class ThreadJoinExample extends Thread {
    public static void main(String[] args) throws InterruptedException {
        Thread targetThread=new ThreadJoinExample();
        targetThread.start();
        targetThread.join();
       //main thread will wait until the completion of a thread execution.
        System.out.println("main thread resuming the execution");
        System.out.println("main thread completed its execution");
    }
    public void run()
    {
    System.out.println("Target Thread entered the run method");
    System.out.println("Target Thread completing the execution of a run method");
    }
}

Output:

Target Thread entered the run method
Target Thread completing the execution of a run method
main thread resuming the execution
main thread completed its execution

Explanation:

In the above example, we have created class named as ThreadJoinExample which extends Thread class, created a new thread. Before creating new thread, we have one main thread after creating new one total is two. Main thread invoked join method of new thread, and hence main thread will wait until complete execution of new thread.

Benefits of join method

  1. Allows communication between two threads.
  2. Better control as compared to the sleep method.
  3. Zero wastage of CPU cycles.

Conclusion

We learned about the use case of java.lang.Thread join method, benefits of join method as compared to the sleep method. And learned the implementation with the help of working examples.