Java threadJoinThe method can be used to pause the execution of the current thread until the target thread dies. There are three join overload methods in Thread.
Public final void join (): This method puts the current thread into the waiting queue until the thread called by it dies. If the thread is interrupted, an InterruptedException exception is thrown.
Public final synchronized void join (long millis): This method is used to bring the current thread into the waiting state until the thread called by it dies or goes through millis milliseconds. Because the thread execution depends on the operating system, this method cannot ensure that the waiting time of the current thread is consistent with the specified time.
Public final synchronized void join (long millis, int nanos): This method is used to pause a thread in millis millisecond nanos nanoseconds.
The following example demonstrates the use of the join method. The purpose of this section of code is to ensure that the main thread ends at the end, and the third thread can be started only when the first thread dies.
ThreadJoinExample. java
package com.journaldev.threads;public class ThreadJoinExample { Thread t1 = new Thread(new MyRunnable(), "t1"); Thread t2 = new Thread(new MyRunnable(), "t2"); Thread t3 = new Thread(new MyRunnable(), "t3"); t1.start(); //start second thread after waiting for 2 seconds or if it's dead try { t1.join(2000); } catch (InterruptedException e) { e.printStackTrace(); } t2.start(); //start third thread only when first thread is dead try { t1.join(); } catch (InterruptedException e) { e.printStackTrace(); } t3.start(); //let all threads finish execution before finishing main thread try { t1.join(); t2.join(); t3.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("All threads are dead, exiting main thread");}class MyRunnable implements Runnable { @Override public void run() { System.out.println("Thread started:::" + Thread.currentThread.getName()); try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread ended:::" + Thread.currentThread.getName()); }}
The output result of the above program is:
Thread started:::t1Thread started:::t2Thread ended:::t1Thread started:::t3Thread ended:::t2Thread ended:::t3All threads are dead, exiting main thread
Original article address: Java Thread Join Example with Explanation