join() method of the Thread class can be used to join the execution of the currently running thread at end of the execution of some other thread. if you call the join() method on any thread object, the currently running thread will go to sleep (or hold) until that thread object complete its execution. once the its execution is completed, the sleeping/hold thread will resume its execution.
In order to understand the functionality of the join() method clearly, please look at the below sample program.
public class Application | |
{ | |
public static void main(String[] args) | |
{ | |
System.out.println("Main thread started "); | |
ThreadA threadA = new ThreadA(); | |
threadA.start(); | |
System.out.println("ThreadA was started"); | |
try { | |
System.out.println("Main thread is waiting until ThreadA completes"); | |
threadA.join(); | |
System.out.println("Main thread resumed again after completing ThreadA"); | |
} catch (InterruptedException e) { | |
System.out.println("waiting thread interrupted "); | |
} | |
System.out.println("Main thread completed "); | |
} | |
} | |
class ThreadA extends Thread | |
{ | |
public void run() | |
{ | |
System.out.println("ThreadA is running"); | |
try { | |
System.out.println("ThreadA sleeps for 5 seconds"); | |
Thread.sleep(5000); | |
} catch (InterruptedException e) { | |
System.out.println("sleeping thread interrupted "); | |
} | |
System.out.println("ThreadA completed"); | |
} | |
} |
The main method (main thread) of the Application class has created an instance of ThreadA and started it. as soon as it is started, the main thread has invoked join() method on it. please check the below code segment of the line number 13.
threadA.join();
Once it is called, the currently running thread ( that is the main thread) will hold its execution and wait until threadA completes its execution. After threadA going to the dead state, the main thread will be resumed.
if you run the above program, you will get the following output and you can examine the output with the above code.
Main thread started ThreadA is running ThreadA sleeps for 5 seconds ThreadA was started Main thread is waiting until ThreadA completes ThreadA completed Main thread resumed again after completing ThreadA Main thread completed
One thought on “Java Thread : join() example”