Thread join() Method in JAVA

join() Method in JAVA

The join() method provided by the java.lang.Thread class is used to hold the execution of currently running thread until the specified thread has finished execution or terminated.

The join() method throws an InterruptedException.

Example of join()

Program(Save as Main.java)

class threadJoin implements Runnable
{ 
    public void run()
    { 
        for(int i=1;i<=3;i++)
        { 
            System.out.println(Thread.currentThread().getName()+" is running and value = "+i+" "); 
            try{ 
                Thread.sleep(500);
            }  
            catch(InterruptedException e){} 
        }
    }
}
class Main
{
    public static void main(String args[]) throws InterruptedException
    {   
        threadJoin obj = new threadJoin();
        Thread t1 = new Thread(obj);
        Thread t2 = new Thread(obj);
        t1.start();
        t1.join();
        t2.start(); 
    } 
}

Output

Thread-0 is running and value = 1
Thread-0 is running and value = 2
Thread-0 is running and value = 3
Thread-1 is running and value = 1
Thread-1 is running and value = 2
Thread-1 is running and value = 3

In the above, program we have created two threads t1(Thread-0) and t2(Thread-1). When we call t1.start(), Thread-0 begins executing. t1.join() makes sure that the thread t1(Thread-0) completes its execution before thread t2(Thread-1) begins executing.

Hence we get a sequential output, instead of a random output. Remove the join() method and see what happens.

Share Me!