Joining Threads in Java

17 Feb, 2021
java.lang.Thread class provides the join() method which allows one thread to wait until another thread completes its execution. If t is a Thread object whose thread is currently executing, then t.join() will make sure that t is terminated before the next instruction is executed by the program.If there are multiple threads calling the join() methods that means overloading on join allows the programmer to specify a waiting period. However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify.There are three overloaded join functions.
join(): It will put the current thread on wait until the thread on which it is called is dead. If thread is interrupted then it will throw InterruptedException.Syntax:public final void join()
join(long millis) :It will put the current thread on wait until the thread on which it is called is dead or wait for specified time (milliseconds).Syntax:public final synchronized void join(long millis)
join(long millis, int nanos): It will put the current thread on wait until the thread on which it is called is dead or wait for specified time (milliseconds + nanos).Syntax:public final synchronized void join(long millis, int nanos)
// Java program to explain the// concept of joining a thread.import java.io.*;  // Creating thread by creating the// objects of that classclass ThreadJoining extends Thread{    @Override    public void run()    {        for (int i = 0; i < 2; i++)        {            try            {                Thread.sleep(500);                System.out.println("Current Thread: "                        + Thread.currentThread().getName());            }              catch(Exception ex)            {                System.out.println("Exception has" +                                " been caught" + ex);            }            System.out.println(i);        }    }}  class GFG{    public static void main (String[] args)    {          // creating two threads        ThreadJoining t1 = new ThreadJoining();        ThreadJoining t2 = new ThreadJoining();        ThreadJoining t3 = new ThreadJoining();          // thread t1 starts        t1.start();          // starts second thread after when        // first thread t1 has died.        try        {            System.out.println("Current Thread: "                  + Thread.currentThread().getName());            t1.join();        }          catch(Exception ex)        {            System.out.println("Exception has " +                                "been caught" + ex);        }          // t2 starts        t2.start();          // starts t3 after when thread t2 has died.        try        {            System.out.println("Current Thread: "                 + Thread.currentThread().getName());            t2.join();        }          catch(Exception ex)        {            System.out.println("Exception has been" +                                    " caught" + ex);        }          t3.start();    }}output:Current Thread: main
Current Thread: Thread-0
0
Current Thread: Thread-0
1
Current Thread: main
Current Thread: Thread-1
0
Current Thread: Thread-1
1
Current Thread: Thread-2
0
Current Thread: Thread-2
1

join(): It will put the current thread on wait until the thread on which it is called is dead. If thread is interrupted then it will throw InterruptedException.Syntax:public final void join()

public final void join()

join(long millis) :It will put the current thread on wait until the thread on which it is called is dead or wait for specified time (milliseconds).Syntax:public final synchronized void join(long millis)

public final synchronized void join(long millis)

join(long millis, int nanos): It will put the current thread on wait until the thread on which it is called is dead or wait for specified time (milliseconds + nanos).Syntax:public final synchronized void join(long millis, int nanos)
// Java program to explain the// concept of joining a thread.import java.io.*;  // Creating thread by creating the// objects of that classclass ThreadJoining extends Thread{    @Override    public void run()    {        for (int i = 0; i < 2; i++)        {            try            {                Thread.sleep(500);                System.out.println("Current Thread: "                        + Thread.currentThread().getName());            }              catch(Exception ex)            {                System.out.println("Exception has" +                                " been caught" + ex);            }            System.out.println(i);        }    }}  class GFG{    public static void main (String[] args)    {          // creating two threads        ThreadJoining t1 = new ThreadJoining();        ThreadJoining t2 = new ThreadJoining();        ThreadJoining t3 = new ThreadJoining();          // thread t1 starts        t1.start();          // starts second thread after when        // first thread t1 has died.        try        {            System.out.println("Current Thread: "                  + Thread.currentThread().getName());            t1.join();        }          catch(Exception ex)        {            System.out.println("Exception has " +                                "been caught" + ex);        }          // t2 starts        t2.start();          // starts t3 after when thread t2 has died.        try        {            System.out.println("Current Thread: "                 + Thread.currentThread().getName());            t2.join();        }          catch(Exception ex)        {            System.out.println("Exception has been" +                                    " caught" + ex);        }          t3.start();    }}output:Current Thread: main
Current Thread: Thread-0
0
Current Thread: Thread-0
1
Current Thread: main
Current Thread: Thread-1
0
Current Thread: Thread-1
1
Current Thread: Thread-2
0
Current Thread: Thread-2
1

public final synchronized void join(long millis, int nanos)

// Java program to explain the// concept of joining a thread.import java.io.*;  // Creating thread by creating the// objects of that classclass ThreadJoining extends Thread{    @Override    public void run()    {        for (int i = 0; i < 2; i++)        {            try            {                Thread.sleep(500);                System.out.println("Current Thread: "                        + Thread.currentThread().getName());            }              catch(Exception ex)            {                System.out.println("Exception has" +                                " been caught" + ex);            }            System.out.println(i);        }    }}  class GFG{    public static void main (String[] args)    {          // creating two threads        ThreadJoining t1 = new ThreadJoining();        ThreadJoining t2 = new ThreadJoining();        ThreadJoining t3 = new ThreadJoining();          // thread t1 starts        t1.start();          // starts second thread after when        // first thread t1 has died.        try        {            System.out.println("Current Thread: "                  + Thread.currentThread().getName());            t1.join();        }          catch(Exception ex)        {            System.out.println("Exception has " +                                "been caught" + ex);        }          // t2 starts        t2.start();          // starts t3 after when thread t2 has died.        try        {            System.out.println("Current Thread: "                 + Thread.currentThread().getName());            t2.join();        }          catch(Exception ex)        {            System.out.println("Exception has been" +                                    " caught" + ex);        }          t3.start();    }}
output:
Current Thread: main
Current Thread: Thread-0
0
Current Thread: Thread-0
1
Current Thread: main
Current Thread: Thread-1
0
Current Thread: Thread-1
1
Current Thread: Thread-2
0
Current Thread: Thread-2
1

In the above example we can see clearly second thread t2 starts after first thread t1 has died and t3 will start its execution after second thread t2 has died.Thread Join | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersThread Join | GeeksforGeeksWatch laterShareCopy link10/10InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:34•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ruXbPdOST4A" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
mucunguzia
Ammar Githam
Java-Multithreading
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.