Tutorial

Java Thread Join Example

Published on August 4, 2022
author

Pankaj

Java Thread Join Example

Java Thread join method can be used to pause the current thread execution until unless the specified thread is dead. There are three overloaded join functions.

Java Thread join

java thread join, thread join example, java thread join example, thread join public final void join(): This java thread join method puts the current thread on wait until the thread on which it’s called is dead. If the thread is interrupted, it throws InterruptedException. public final synchronized void join(long millis): This java thread join method is used to wait for the thread on which it’s called to be dead or wait for specified milliseconds. Since thread execution depends on OS implementation, it doesn’t guarantee that the current thread will wait only for given time. public final synchronized void join(long millis, int nanos): This java thread join method is used to wait for thread to die for given milliseconds plus nanoseconds. Here is a simple example showing usage of Thread join methods. The goal of the program is to make sure main is the last thread to finish and third thread starts only when first one is dead.

package com.journaldev.threads;

public class ThreadJoinExample {

    public static void main(String[] args) {
        Thread t1 = new Thread(new MyRunnable(), "t1");
        Thread t2 = new Thread(new MyRunnable(), "t2");
        Thread t3 = new Thread(new MyRunnable(), "t3");
        
        t1.start();
        
        //start second thread after waiting for 2 seconds or if it's dead
        try {
            t1.join(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        t2.start();
        
        //start third thread only when first thread is dead
        try {
            t1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        t3.start();
        
        //let all threads finish execution before finishing main thread
        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        System.out.println("All threads are dead, exiting main thread");
    }

}

class MyRunnable implements Runnable{

    @Override
    public void run() {
        System.out.println("Thread started:::"+Thread.currentThread().getName());
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Thread ended:::"+Thread.currentThread().getName());
    }
    
}

Output of the above program is:

Thread started:::t1
Thread started:::t2
Thread ended:::t1
Thread started:::t3
Thread ended:::t2
Thread ended:::t3
All threads are dead, exiting main thread

That’s all for a quick roundup on java thread join example.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Category:
Tutorial
Tags:

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
February 3, 2013

Here: //let all threads finish execution before finishing main thread try { t1.join(); t2.join(); t3.join(); Do you really need to check if thread 1 as ended ? Isn’t T1 suppoed to end before T3 starts in code ? Maybe I am overlooking something.

- Rajesh

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
February 3, 2013

It’s just an example code to understand the Thread join() method. Yes you are right, since t1.join() is already called, it’s dead so we can just call join methods on t2 and t3.

- Pankaj

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    July 16, 2013

    Line 10: t1 starts Line 14: main thread waits till t1 ends Line 19: t1 ended, main thread starts t2 Line 23: TYPO?? t2.join() will cause main thread to wait till t2 ends Line 28: t2 ended, main thread starts t3 Line 32: no use of it Line 33: no use of it Line 34: main thread will wait till t3 ends

    - Amitabha Roy

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    June 2, 2019

    Good one

    - peng li

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      January 2, 2014

      Hi I have one question like Why sleep and yield methods are static?

      - swamy

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      January 2, 2014

      If you will look into the sleep() and yield() method details, they work on the current executing thread, so there is no point in calling these methods on some other threads that are not executing i.e in wait state. That’s why these methods are made static so that when this method is called statically, it works on the current executing thread and avoid confusion to the programmers who might think that they can invoke these methods on some non-running threads. It’s a very interesting question and that’s why it’s part of https://www.journaldev.com/1162/java-multi-threading-concurrency-interview-questions-with-answers

      - Pankaj

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        January 10, 2014

        Thread started : t1 time : Fri Jan 10 18:49:30 IST 2014 Thread started : t2 time : Fri Jan 10 18:49:32 IST 2014 Thread ended : t1 time : Fri Jan 10 18:49:34 IST 2014 Thread started : t3 time : Fri Jan 10 18:49:34 IST 2014 Thread ended : t2 time : Fri Jan 10 18:49:36 IST 2014 Thread ended : t3 time : Fri Jan 10 18:49:38 IST 2014

        - Preetam

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        January 10, 2014

        t1 waits only for 2 seconds before t2 starts

        - Preetam

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        May 7, 2015

        m1 m1 main end t1 t1 t1 t1 t2 t2 t2 t2 t3 t3 t3 t3 Thread started:::t1 Thu May 07 11:00:09 CST 2015 Thread started:::t2 Thu May 07 11:00:11 CST 2015 Thread ended:::t1 Thu May 07 11:00:13 CST 2015 Thread started:::t3 Thu May 07 11:00:13 CST 2015 Thread ended:::t2 Thu May 07 11:00:15 CST 2015 Thread ended:::t3 Thu May 07 11:00:17 CST 2015 All threads are dead, exiting main thread

        - Issac

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          February 3, 2014

          There maybe a small mistake about the description of the 3 overloaded functions. They are all “public final void” method in Java doc: https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html. Any special thought add “synchronized” here? BTW, I found this post from another one given by you: Multi-Threading and Concurrency Interview Questions with Answers. It helped me a lot for understanding java thread. Thanks a lot!

          - LinTao

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          February 3, 2014

          The method syntax is correct, please check the Thread class source code.

          - Pankaj

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          March 1, 2015

          I’ve just check the Harmony code. FYI, the 3 methods are declared as this: public final synchronized void join() throws InterruptedException public final void join(long timeoutInMilliseconds) throws InterruptedException public final synchronized void join(long timeoutInMilliseconds, int nanos) throws InterruptedException

          - LinTao

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            May 3, 2014

            Would you explain to me: when we use join() method in this example, we say to main method (but not some other thread) to wait until some thread died or some time passed ? - so every call join() we do from main method or we call it from the thread we recently started ? And on the line 32 “t1.join();” - if we comment that, it will not break anything ?

            - Mark

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              June 11, 2014

              Hi Pankaj, Could you please explain the difference between t1,join(2000) and Thread.sleep(2000), in both the cases, the current thread waits for 2000 ms. Is there any difference in terms of locks or resources? Regards, Amishi

              - Amishi Shah

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              June 11, 2014

              Both are completely different things, sleep() causes current thread to wait for given time. join() is used with wait for another thread to complete execution or wait for given time. For example, in above program main() thread is using join() to wait for other threads to finish.

              - Pankaj

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                September 17, 2014

                thanks

                - Deepak

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  September 21, 2014

                  How Can make sure the order of execution of the threads? First t1 should execute,then t2 and then t2 using join method

                  - srini

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  June 13, 2016

                  call t1.join() before calling t2.start() and so on.

                  - Pankaj

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    October 20, 2014

                    t1.join() is not required for the main thread to be end as t3.start() already took care of t1 dead state.

                    - Ramakant

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    June 13, 2016

                    Yes you are right, put some join method with time and check the output to learn more. The example code is to understand the join method.

                    - Pankaj

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      November 4, 2014

                      I am curious why t3.join() can be called when t2.join() is already called. I mean doesn’t t2.join() block main thread? If that’s the case, why can the main thread proceed to execute t3.join()?

                      - George Chou

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        June 9, 2015

                        t1.join(2000); means… does the t1 joins the main method ?

                        - Balaji

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          June 12, 2015

                          HI pankaj After going through ur code i was having certain doubts over the order of output you provided here so i ran the same code on my machine and the correct order of output is this : Thread started:::t1 Thread started:::t2 Thread ended:::t1 Thread started:::t3 Thread ended:::t2 Thread ended:::t3 All threads are dead, exiting main thread Thread t1 doesn’t end until thread t2 starts. I think that’s because while t1 goes to sleep for 4000 millisec main thread is still executing and as soon as it encounters t1.join(2000) it stops its own execution for the same time period but, thread t1 still has to wait for another 2000 millisec before completion. Meanwhile t2 starts and before t1 could complete its execution the line prints Thread started::::t2 For 2000 millisec the t1 thread’s sleep execution and t1’s join execution run in parallel Tell me if the above explanation is wrong.

                          - GreatestJoy

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            August 26, 2015

                            I have doubt if we called join() without thread refference just like public void m1()throws Exception { join(); } what happened

                            - guru ghule

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              September 4, 2015

                              Simple but informative article:) Keep up the good work bro:) If possible pls add more articles to collection framework internals.

                              - Gopinath

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                September 25, 2015

                                U are fab pankaj.

                                - kumkum

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  October 18, 2015

                                  Great explanations.This is wat needed…

                                  - pradpalnis

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    July 25, 2016

                                    Best Example so Far. Thanks a lot to making join looks so easy.

                                    - Kamal Thakur

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      November 11, 2016

                                      Hi, I have one question in this, if t1 thread execution fails with NullPointer Exception , I need to stop the main thread or we have to capture wich thread is failed. Could you please explains this.

                                      - Eswar

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        September 21, 2017

                                        I have one doubt, as we can see in the implementation of the join() method , it waits until thread isAlive() method returen true. Now the question is when wait() is called on instance of the thread , it would be disabled for thread scheduling, So if i am calling join() on any thread instance , would it ever get chance to execute the code in run method as it is waiting in a loop over isAlive() method.

                                        - Siddharth

                                          Try DigitalOcean for free

                                          Click below to sign up and get $200 of credit to try our products over 60 days!

                                          Sign up

                                          Join the Tech Talk
                                          Success! Thank you! Please check your email for further details.

                                          Please complete your information!

                                          Become a contributor for community

                                          Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                                          DigitalOcean Documentation

                                          Full documentation for every DigitalOcean product.

                                          Resources for startups and SMBs

                                          The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                          Get our newsletter

                                          Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                          New accounts only. By submitting your email you agree to our Privacy Policy

                                          The developer cloud

                                          Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                          Get started for free

                                          Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                          *This promotional offer applies to new accounts only.