Blogger

Delete comment from: Javarevisited

Anonymous said...

TO make sure T1, T2 and T3 finishes in same order, you need to call T1.join() in T2, T2.join() in T3 and T3.join() in main thread. The logic here is you need to call join on one thread from run method of another thread. Here, I am providing a sample code. I hope it helps.

class ThreadOrder implements Runnable {

Thread waitOn;

public ThreadOrder(Thread waitOn) {
this.waitOn = waitOn;
}

@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " started");
for (int i = 1; i <= 4; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {

e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ": " + i);
}
if (waitOn != null) {
try {
waitOn.join();
} catch (InterruptedException e) {

e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " complete");
}
}

public class JoinTest {

public static void main(String[] args) throws InterruptedException {

System.out.println(Thread.currentThread().getName() + " started");

Thread t1 = new Thread(new ThreadOrder(null), "one");
Thread t2 = new Thread(new ThreadOrder(t1), "two");
Thread t3 = new Thread(new ThreadOrder(t2), "three");

t1.start();
t2.start();
t3.start();

for (int i = 1; i <= 4; i++) {

Thread.sleep(500);

System.out.println(Thread.currentThread().getName() + ": " + i);
}

t3.join();

System.out.println("main complete");

}

}

Aug 15, 2016, 9:33:39 AM


Posted to How to Join Multiple Threads in Java? [Thread.join() Example]

Google apps
Main menu