«Back to Home

Core Java

Topics

join() Method In Java

join() method

The join() method is mainly used to hold the execution of currently running thread until the specified thread is dead.
 
In other words, we can say that join() method waits for a thread to die and It causes the presently running threads to stop until the thread it joins which finishes its entire task.
 
Syntax

public void join()throws InterruptedException
 
public void join(long milliseconds)throws InterruptedException
 
Let’s see an example of join() method.
 
Code
  1. public class JoinMethod extends Thread {  
  2.     public void run() {  
  3.         for (int i = 0; i <= 6; i++) {  
  4.             try {  
  5.                 Thread.sleep(1000);  
  6.             } catch (Exception e) {  
  7.                 System.out.println(e);  
  8.             }  
  9.             System.out.println(i);  
  10.         }  
  11.     }  
  12.     public static void main(String args[]) {  
  13.         JoinMethod t1 = new JoinMethod();  
  14.         JoinMethod t2 = new JoinMethod();  
  15.         JoinMethod t3 = new JoinMethod();  
  16.         t1.start();  
  17.         try {  
  18.             t1.join();  
  19.         } catch (Exception e) {  
  20.             System.out.println(e);  
  21.         }  
  22.   
  23.         t2.start();  
  24.         t3.start();  
  25.     }  
  26. }  
15

Output

17

In the above example, we can observe that when t1 completes its task then t2 and t3 starts executing.
 
Let’s see an example of join(long miliseconds) method, given below.
 
Code
  1. public class JoinMethod extends Thread {  
  2.     public void run() {  
  3.         for (int i = 0; i <= 4; i++) {  
  4.             try {  
  5.                 Thread.sleep(700);  
  6.             } catch (Exception e) {  
  7.                 System.out.println(e);  
  8.             }  
  9.             System.out.println(i);  
  10.         }  
  11.     }  
  12.   
  13.     public static void main(String args[]) {  
  14.         JoinMethod t1 = new JoinMethod();  
  15.         JoinMethod t2 = new JoinMethod();  
  16.         JoinMethod t3 = new JoinMethod();  
  17.         t1.start();  
  18.         try {  
  19.             t1.join(1000);  
  20.         } catch (Exception e) {  
  21.             System.out.println(e);  
  22.         }  
  23.         t2.start();  
  24.         t3.start();  
  25.     }  
  26. }  
16
Output

18

In the above example, t1 is completes its task for 1000 miliseconds then t2 and t3 starts executing.
 
Summary

Thus, we learnt, join() method is mainly used to hold the execution of currently running thread until the specified thread is dead and also learnt, how to use join() method in Java.