Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to show the use of join method

Java Code Example — Multithreading Programs

ADVERTISEMENT

Java Program to show the use of join method

Objective

Write a Java program to demonstrate the join() method in Multithreading.

Algorithm / Approach

  1. Create a thread class and instantiate three threads (t, t2, t3).
  2. Start the first thread: t.start().
  3. Immediately call t.join() inside a try-catch block.
  4. After the join block, start the other two threads: t2.start() and t3.start().
Test.java
class  Test extends Thread{
 char x;
 Test(char a) {
  x = a;
 }
 public void run(){
  for(int i =0 ; i< 5; i++) {
   System.out.println(x+" "+i);
  }
 }
 public static void main(String[] a)
 {
  Test t= new Test('X');
  Test t2 = new Test('Y');
  Test t3 = new Test('Z');
  t.start(); 
  try {
   t.join();
  }
  catch(Exception e) {
   System.out.println("Exception Occured");
  }
  t2.start();
  t3.start();
 }
}

Expected Output

<b>Note:- Output will not be fixed</b>                            
X 0
X 1
X 2
X 3
X 4
Z 0
Z 1
Z 2
Y 0
Z 3
Y 1
Z 4
Y 2
Y 3
Y 4

Explanation of the Program

  • The join() method forces the current executing thread (in this case, the Main thread) to pause and wait until the thread on which join() was called (thread t) completely finishes its execution.
  • Because of t.join(), thread t is guaranteed to finish printing all of its "X"s before threads t2 and t3 are even allowed to start.
  • Once t finishes, t2 and t3 start simultaneously, and their outputs will be randomly interleaved.

Complexity

Time Complexity O(n)
Space Complexity O(1)

Common Mistakes

  • Forgetting to wrap join() in a try-catch block. The join() method throws a checked InterruptedException which must be handled.
ADVERTISEMENT