What is Java Thread Join method and its purpose? – Clear Example

(Last Updated On: October 23, 2018)

In java Thread join method is used, so that main or parent thread can wait for its child thread to finish its execution and die. After that only main thread can executes its further statements.

For example,

In below thread program, main () method in Sample class is the main thread and it is creating and starting a child thread. Child thread will execute the Task (statements within the run () method of Task class).

Since, main thread wants to wait for its child to complete its execution and die, so, it will call join () method on child thread object t1. e.g. t1.join().

Once child thread is done, then main will execute its further statements.

 

What child thread is doing in run () method?

Child thread in run method running a while loop 5 times, printing “My Thread” on console and waiting for 5 seconds using java Thread.sleep() method.

Here is the output of below program.

Main Thread Started
Child Thread Started
Main is waiting for child thread to finish
My Thread
My Thread
My Thread
My Thread
My Thread
Main Thread ends

Notice that main thread is waiting for child thread to finish. once child thread is done, only then main thread is executing.

Java Thread Join Example

 

Overloaded Thread join methods

There are 3 overloaded join () methods in Thread class as below

join() : Parent thread wait till its child is finish execution and die.

join(long millis) : Parent thread will only wait for the mention time to finish the child thread. If child thread still working after mentioned time, then, parent thread will stop waiting and will start executing its further statements.

join(long millis, int nanos): It does the same as above , and can wait for another nano seconds given.

For example, join(2000, 500),means , the parent will wait for 2 seconds + 500 nano seconds. after that it will stop waiting.

Example,

If you replace the code t1.join() with t1.join(2000). main thread will only wait for 2 seconds to child thread to die and executes its further statements.

Here is the output on replacement

Main Thread Started
Child Thread Started
Main is waiting for child thread to finish
My Thread
Main Thread ends
My Thread
My Thread
My Thread
My Thread

NOTES:

  • Notice that if there are 2 child threads t1 and t2 (as an example) and if main thread is calling join() method on t1 child thread only, then, main thread will wait for only t1 thread to die not for t2 thread.
  • If thread is interrupted, then it will throw InterruptedException. You can notice throws interrupted exception is add in main() method. e.g. public static void main(String[] args) throws