Java Program to show the use of join method
Objective
Write a Java program to demonstrate the join() method in Multithreading.
Algorithm / Approach
- Create a thread class and instantiate three threads (t, t2, t3).
- Start the first thread:
t.start(). - Immediately call
t.join()inside a try-catch block. - After the join block, start the other two threads:
t2.start()andt3.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 whichjoin()was called (threadt) completely finishes its execution. - Because of
t.join(), threadtis guaranteed to finish printing all of its "X"s before threadst2andt3are even allowed to start. - Once
tfinishes,t2andt3start 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. Thejoin()method throws a checkedInterruptedExceptionwhich must be handled.