Join is method from thread class. It can be called on thread object and when it is called, current thread will wait for other thread (on which join is called) to finish execution.


Use Case :-


With help of join, you can introduce element of serialization in multi-threading environment.


For Example :-


Example shows two threads Bruno and Adam. Bruno starts first and then we call join on it. So thread in current execution will wait for Bruno to finish and then resume execution further.



package com.techiekunal.examples;

public class JoinExample {

 class MyRunnable implements Runnable {
  
  @Override
  public void run() {
   System.out.println("Executing Thread is :- " + Thread.currentThread().getName());
   try {
    if(Thread.currentThread().getName().equals("Bruno"))
     Thread.sleep(2000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   System.out.println("Executing Complete. Thread is :- " + Thread.currentThread().getName());
  }
 }
 
 public static void main(String[] args) {
  
  Thread t1 = new Thread(new JoinExample().new MyRunnable(),"Bruno");
  Thread t2 = new Thread(new JoinExample().new MyRunnable(),"Adam");
  
  t1.start();
  try {
   t1.join();
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  t2.start();
 }
}


Output


Executing Thread is :- Bruno
Executing Complete. Thread is :- Bruno
Executing Thread is :- Adam
Executing Complete. Thread is :- Adam