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 authors
Default avatar
Pankaj

author

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
    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
      January 2, 2014

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

      - swamy

        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
          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
            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
                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
                    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

                      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.