BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Thread join() method in Java with example

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

The join() method is used to hold the execution of currently running thread until the specified thread is dead(finished execution). In this tutorial we will discuss the purpose and use of join() method with examples.

Why we use join() method?

In normal circumstances we generally have more than one thread, thread scheduler schedules the threads, which does not guarantee the order of execution of threads.
For example lets have a look at the following code:

Without using join()

Here we have three threads th1, th2 and th3. Even though we have started the threads in a sequential manner the thread scheduler does not start and end them in the specified order. Everytime you run this code, you may get a different result each time. So the question is: How can we make sure that the threads executes in a particular order. The Answer is: By using join() method appropriately.

public class JoinExample2 {
   public static void main(String[] args) {
      Thread th1 = new Thread(new MyClass2(), "th1");
      Thread th2 = new Thread(new MyClass2(), "th2");
      Thread th3 = new Thread(new MyClass2(), "th3");
         
      th1.start();
      th2.start();        
      th3.start();
   }
}
 
class MyClass2 implements Runnable{
 
    @Override
    public void run() {
    	Thread t = Thread.currentThread();
        System.out.println("Thread started: "+t.getName());
        try {
            Thread.sleep(4000);
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }
        System.out.println("Thread ended: "+t.getName());    
    }
}

Output:

Thread started: th1
Thread started: th3
Thread started: th2
Thread ended: th1
Thread ended: th3
Thread ended: th2

Lets have a look at the another code where we are using the join() method.

The same example with join()

Lets say our requirement is to execute them in the order of first, second and third. We can do so by using join() method appropriately.

public class JoinExample {
   public static void main(String[] args) {
      Thread th1 = new Thread(new MyClass(), "th1");
      Thread th2 = new Thread(new MyClass(), "th2");
      Thread th3 = new Thread(new MyClass(), "th3");
         
      // Start first thread immediately
      th1.start();
         
      /* Start second thread(th2) once first thread(th1) 
       * is dead
       */
      try {
          th1.join();
      } catch (InterruptedException ie) {
          ie.printStackTrace();
        }
      th2.start();
         
      /* Start third thread(th3) once second thread(th2) 
       * is dead
       */
      try {
          th2.join();
      } catch (InterruptedException ie) {
           ie.printStackTrace();
        }
      th3.start();
         
      // Displaying a message once third thread is dead
      try {
          th3.join();
      } catch (InterruptedException ie) {
            ie.printStackTrace();
        }  
      System.out.println("All three threads have finished execution");
   }
}
 
class MyClass implements Runnable{
 
    @Override
    public void run() {
    	Thread t = Thread.currentThread();
        System.out.println("Thread started: "+t.getName());
        try {
            Thread.sleep(4000);
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }
        System.out.println("Thread ended: "+t.getName());
        
    }
}

Output:

Thread started: th1
Thread ended: th1
Thread started: th2
Thread ended: th2
Thread started: th3
Thread ended: th3
All three threads have finished execution

In this example we have used the join() method in such a way that our threads execute in the specified order.

Top Related Articles:

  1. OOPs in Java: Encapsulation, Inheritance, Polymorphism, Abstraction
  2. Can we start a Thread twice in Java?
  3. What is the difference between a process and a thread in Java?
  4. Basics: All about Java threads
  5. Polymorphism in Java with example

Tags: Java-Multithreading

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. AKshay says

    June 27, 2016 at 2:44 PM

    Thank you very much!!! It was very helpful…

    Reply
  2. nishant says

    November 11, 2016 at 8:56 AM

    Nice example,very helpful in understanding concept about join() method.

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap