How do I use join method to wait for threads to finish?

If you want a thread to work until another thread dies, you can join the thread onto the end of the another thread using the join() method. For example, you want thread B only work until thread A completes its work, then you want thread B to join thread A.

package org.kodejava.example.lang;

public class ThreadJoin implements Runnable {
    private int numberOfLoop;

    public ThreadJoin(int numberOfLoop) {
        this.numberOfLoop = numberOfLoop;
    }

    public void run() {
        System.out.println("[" +
                Thread.currentThread().getName() + "] - Running.");

        for (int i = 0; i < this.numberOfLoop; i++) {
            System.out.println("[" +
                    Thread.currentThread().getName() + "] " + i);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("[" +
                Thread.currentThread().getName() + "] - Done.");
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new ThreadJoin(10), "FirstThread");
        Thread t2 = new Thread(new ThreadJoin(20), "SecondThread");

        try {
            //
            // start t1 and waits for this thread to die before
            // starting the t2 thread.
            //
            t1.start();
            t1.join();

            // start t2
            t2.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply