The Java Thread join method is used to pause the current thread until the thread on the join operation ends. There are three overloaded join methods in Java:
public final void join(): this method will change the current thread to wait until the end of the thread executing the join operation. If the thread is interrupted during execution, InterruptedException will be thrown.
public final synchronized void join(long millis): this method will change the current thread to wait until the end of the thread executing the join operation or wait for millis after the join operation. Because thread scheduling depends on the implementation of the operating system, this does not guarantee that the current thread will become RUnnable at millis time.
Public final synchronized void join (long millis, int nanos): this method will change the current thread to wait until the thread executing the join operation ends or waits for millis+nanos after the join.
The following example program shows the use of the Thread join method. In this program, the main thread should be the last completed thread, and the third thread should not be executed until the first thread is finished.
package com.journaldev.threads;
public class ThreadJoinExample {
public static void main(String[] args) {
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) {
// TODO Auto-generated catch block
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 of the program is as follows:
Thread started:::t1 Thread ended:::t1 Thread started:::t2 Thread started:::t3 Thread ended:::t2 Thread ended:::t3 All threads are dead, exiting main thread