In Java, execution of the program starts from main() method. From which all remaining threads are created, these remaining threads are considered to be the child threads of the main thread. The child threads are started after the main thread.

All threads are executed independently and each thread has their own thread life cycle, hence every thread can stop at any point of time (after it task has completed). But what about the main thread if it stopped, all the child threads are terminated. For this case, the main thread should wait until all the child threads are completed their task. The join() method is used to achieve this task.

Syntax:

final void join() throws InterruptedException

final void join(long mils) throws InterruptedException

final void join(long mils,int ns) throws InterruptedException

If a thread wants to wait until completing some other thread, then we should go with join() method. the thread join() method is overloaded and every method throws InterruptedException. Hence whenever we use join() we should handle the Exception or throws the Exception.

Thread join

Thread Join

Thread  join Example in Java

JoinDemo.java
class FirstThread extends Thread {

    String threadName;

    public FirstThread(String threadName) {
        this.threadName = threadName;
        System.out.println("Created Thread " + threadName);
    }

    public void run() {
        try {
            for (int i = 0; i < 5; i++) {
                System.out.println("From : " + threadName + " .." + i);
                sleep(1000);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public class JoinDemo {

    public static void main(String[] args) {
        try {
            FirstThread firstThread = new FirstThread("First Thread");
            firstThread.start();
            firstThread.join();
            for (int i = 0; i < 5; i++) {
                System.out.println("Main Thread : " + i);
            }
            System.out.println(" Main Thread : " + Thread.currentThread().isAlive());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Output:


Created Thread First Thread
From : First Thread ..0
From : First Thread ..1
From : First Thread ..2
From : First Thread ..3
From : First Thread ..4
Main Thread : 0
Main Thread : 1
Main Thread : 2
Main Thread : 3
Main Thread : 4
Main Thread : true

On the above Example main thread will wait for execution till the FirstThread complete it task, because we mentioned the firstThread.join(); at line number 33. If we comment the line 33, then two threads are executed simultaneously and we can’t expect the outcome of the program.

You may also Like:

Threads in Java

Java Thread Life Cycle
Happy Learning 🙂