Home » Java Basics » 06 - Threads and GUIs
6

Thread join()

How to use the thread join

There may be situations when the current thread's execution should be halted until another thread 'A' completes execution. This may be accomplished by invoking the join method on thread A. Using A.join() within a thread is tantamount to making the current thread sleep until thread 'A' completes execution. What if the current thread is interrupted before thread 'A' completes execution? Predictably, an interruptedException is thrown.

public class HelloWorldThread extends Thread {
 
public void run() {
System.out.println("Hello World from Thread ");
System.out.println("Thread t about to exit...");
}
 
public static void main(String args[]) {
Thread t = new HelloWorldThread();
t.start();
System.out.println("Hello World from Main Thread");
try {
t.join();
}
catch (InterruptedException ie) {
System.out.println(ie.getMessage());
}
System.out.println("Hello World from Main Thread Again!");
}
 
}

't.join()' makes the main thread waits for thread 't' to complete before 'Hello World from Main Thread Again' is printed again. The following is the output of the above class:

Hello World from Main Thread
Hello World from Thread
Thread t about to exit...
Hello World from Main Thread Again!