Thread.join()
method is used for the same purpose. Docs here.
Lets say tou have Thread T1, T2 and T3.
To finish T3 before T2 and t2 before T1 you need to call T2.join() from T1 and T3.join() from T2. You can do something like below-
public class ThreadSync extends Thread {
Thread waitForThread;
public void setWaitForThread(Thread waitForThread) {
this.waitForThread = waitForThread;
}
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " Thread Started");
if(waitForThread != null)
waitForThread.join();
System.out.println(Thread.currentThread().getName() + " Thread Terminating");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String args[]){
Thread t1 = new ThreadSync();
t1.setName("T1");
Thread t2 = new ThreadSync();
t2.setName("T2");
Thread t3 = new ThreadSync();
t3.setName("T3");
((ThreadSync)t3).setWaitForThread(t2);
((ThreadSync)t2).setWaitForThread(t1);
t1.start();
t2.start();
t3.start();
}
}
Output is
T1 Thread Started
T3 Thread Started
T2 Thread Started
T1 Thread Terminating
T2 Thread Terminating
T3 Thread Terminating