Join Method

This is Second Article in Series of Articles on Java 8 Concurrency Tutorial.

The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing,

t.join();
causes the current thread to pause execution until t’s thread terminates.

Overloads of join allow the programmer to specify a waiting period. However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify.

join responds to an interrupt by exiting with an InterruptedException

Join Method Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14

public class JoinMethodExample {

public static void main(String[] args) {

System.out.println("Main Method Start");

Thread t1 = new Thread(()->System.out.println("Thread Number 1"));
Thread t2 = new Thread(()->System.out.println("Thread Number 2"));
t1.start();
t2.start();
System.out.println("Main Method End");
}
}

If you check output , The main Thread ends before T2 Thread. If you want to wait for Completion of T2 then we need to call join method.

Join Method Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

public class JoinMethodExample {

public static void main(String[] args) {

System.out.println("Main Method Start");

Thread t1 = new Thread(()->System.out.println("Thread Number 1"));
Thread t2 = new Thread(()->System.out.println("Thread Number 2"));
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Main Method End");
}
}
Share Comments