How to join threads in Java Example

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, if you want thread two only work until thread one completes its work, then you want thread two to join thread one.

 
 
package com.java.thread;
 
public class ThreadJoinExample implements Runnable {
 
    private int count;
 
    public ThreadJoinExample(int count) {
        this.count = count;
    }
 
    public void run() {
        System.out.println(Thread.currentThread().getName() + " starting");
        for (int i = 0; i < this.count; i++) {
            System.out.println(Thread.currentThread().getName() + " : " + i);
            try {
                Thread.sleep(20);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + " ending");
    }
 
    public static void main(String[] args) {
        Thread thread1 = new Thread(new ThreadJoinExample(10), "Thread one");
        Thread thread2 = new Thread(new ThreadJoinExample(20), "Thread two");
 
        try {
            thread1.start();
            thread1.join();
 
            thread2.start();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
}
 
 
 

The output of the above example will be as:

 
 
Thread one starting
Thread one : 0
Thread one : 1
Thread one : 2
Thread one : 3
Thread one : 4
Thread one : 5
Thread one : 6
Thread one : 7
Thread one : 8
Thread one : 9
Thread one ending
Thread two starting
Thread two : 0
Thread two : 1
Thread two : 2
Thread two : 3
Thread two : 4
Thread two : 5
Thread two : 6
Thread two : 7
Thread two : 8
Thread two : 9
Thread two : 10
Thread two : 11
Thread two : 12
Thread two : 13
Thread two : 14
Thread two : 15
Thread two : 16
Thread two : 17
Thread two : 18
Thread two : 19
Thread two ending