Java Concurrency - Thread.join()

Thread.join() is the most basic mechanism of inter-thread synchronization in Java.

Thread.join() Method

The calling thread goes into wating state. It waits for the referenced thread to terminate.

Thread.join() throws InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

Example

CountDownRunnable Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class CountDownRunnable implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " - start execution");
for(int i = 3; i >= 0; i--) {
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " - " + i);
} catch (InterruptedException e) {
return; // when interrupted, stop execution and return
}
}
System.out.println(Thread.currentThread().getName() + " - finish execution");
}
}

main method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + " - start execution");

Thread countdownThread = new Thread(new CountDownRunnable(), "countdown");

countdownThread.start();
try {
countdownThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println(Thread.currentThread().getName() + " - finish execution");
}

output

1
2
3
4
5
6
7
8
main - start execution
countdown - start execution
countdown - 3
countdown - 2
countdown - 1
countdown - 0
countdown - finish execution
main - finish execution

if there is no thread join, main thread will finish before countdown thread. see output

1
2
3
4
5
6
7
8
main - start execution
main - finish execution
countdown - start execution
countdown - 3
countdown - 2
countdown - 1
countdown - 0
countdown - finish execution

Thread.join(long millis)

The calling thread goes into wating state. It Waits at most millis milliseconds for the referenced thread to die. A timeout of 0 means to wait forever.

This method is very useful to prevent the calling thread from waiting too long.

1
2
countdownThread.start();
countdownThread.join(1500);

Reference