Thread#join()
halts the calling thread execution until the thread represented by this instance terminates.
That means aThreadInstance.join()
will block the thread in which this method is called until 'aThreadInstance' fishes executing.
public class ThreadJoinExample {
public static void main(String[] args) throws InterruptedException {
Thread threadX = new Thread(() -> runnableLogic());
threadX.start();
// Main thread will wait for the threadX
threadX.join();
System.out.println("Logic after join()");
Thread threadY = new Thread(() -> runnableLogic());
threadY.start();
}
private static void runnableLogic() {
int counter = 0;
System.out.println(Thread.currentThread().getName() + " started ..");
for (int i = 0; i < 1000; i++) {
counter += i;
}
System.out.println(Thread.currentThread().getName() + " ended ..");
}
}
Output:
Thread-0 started.
Thread-0 ended.
after join
Thread-1 started.
Thread-1 ended.
Note Thread-1 starts only after Thread-0 terminates.