Video in progress

What is the join() method used for?

t.join() makes the current thread wait until t finishes. There is a timed version too: join(millis), or join(Duration) in Java 19+.

📖 Answer

Say main has started several threads and needs to collect all of their results:

List<Thread> workers = new ArrayList<>();
for (int i = 0; i < 4; i++) {
    Thread t = new Thread(() -> processChunk());
    workers.add(t);
    t.start();
}
for (Thread t : workers) {
    t.join();   // we wait for each one in turn
}
System.out.println("hammasi tugadi");

After join() returns, all the writes t made are visible to the current thread. That is also a happens-before guarantee, so you can read the result from a plain field.

Note that join() throws InterruptedException. If someone interrupts the waiting thread, the wait stops.

In practice people rarely write join() by hand: if you work with an executor, Future.get(), invokeAll() or CompletableFuture.allOf(...).join() is more convenient.