Thread join() method in Java

In this post, we will see Thread join() method in Java. Let’s see some points related to the join() method.

Thread join() method in Java

  • Method declaration – public final void join() throws InterruptedException.
  • Thread’s join() method have three overloaded versions, all throws InterruptedException(Checked Exception)

join() throws InterruptedException
join(long millis) throws InterruptedException
public final void join(long millis, int nanos) throws InterruptedException

  • What it does – The join() method allows one thread to wait for the completion of another.
  • If a thread wants to wait for the completion of other thread then we can use join() method. For example, if a thread (main thread) wants until completing thread1 then the main thread has to call thread.join().
  • Let’s see an example. First, we will see an example without the join() method, then later we will use the join() method.

Example without join() method –

Output –

main thread
main thread
main thread
main thread
main thread
thread1
thread1
thread1
thread1
thread1

Note – Since both threads will execute simultaneously, the output may vary. It depends on Thread scheduler, which thread will get picked first. For getting the different output you need to execute the program multiple time.

another possible output –

thread1
thread1
thread1
thread1
thread1
main thread
main thread
main thread
main thread
main thread

Example2 – In this example, we are going to use join() method with thread1.

output is –

thread1
thread1
thread1
thread1
thread1
main thread
main thread
main thread
main thread
main thread

Now we have fix output. What’s going on here. Once again just recall what join() method does? The join() method allows one thread to wait for the completion of another thread.  In the above program, when we say one thread that means the main thread and another thread that means thread1. 

Did you notice, In the above program line 16(i.e thread1.join()) is executed by the main thread? So the main thread will wait to completion of another thread(i.e thread1) that’s why in output we have thread1 first.

Let’s see another example –

Output is –

thread1
thread1
thread1
thread1
thread1
thread2
thread2
thread2
thread2
thread2

Note – In the above program we have three threads t.e thread1,thread2 and the main thread. Line number 26 will be executed by the main thread that means the main thread will wait to complete thread1. Once thread1 execution will complete the main thread will execute thread2.

That’s all about Thread join() method in Java.

join() method docs.

Top