Join() in Java

If a Thread wants to wait until the completion of some other Thread, then we can use the Join method. for example if Thread t1 want to waits until completion of Thread t2 then Thread t1 has to call t2.join() , if t1 executes t2.join then immediately t1 will be entered into wait state , once Thread t2 completes its execution , after then t1 will continue its execution

public class JoinMethod extends  Thread{
    @Override
    public void run() {
        for(int i=0;i<5;i++){
            System.out.println("Custom Thread");
        }
        try{
            Thread.sleep(2000);
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}



class TheCodeData{
    public static void main(String[] args) throws InterruptedException {
        JoinMethod t = new JoinMethod();
        t.start();
        t.join();
        for(int i =0;i<5;i++){
            System.out.println("Main Thread");
        }
    }
}

join method java

In the above Example main thread calls join() method on Child thread object hence main thread will wait unitll completion of child thread.

Similar Java Tutorials

Leave a Comment