Java Programs›Multithreading›Wait for Threads Using join()

Wait for Threads Using join() in Java

intermediate·  Multithreading  ·  Concurrency

Problem

join() makes the calling thread wait until the target thread has terminated, which also guarantees that everything the target wrote is visible afterwards.

Sum the numbers 1 to 1000 by giving each half of the array to its own thread, then combine the two partial sums.

Input
1, 2, ..., 1000
Output
125250 + 375250 = 500500

Java Program

Java
public class ThreadJoinExample { public static void main(String[] args) throws InterruptedException { int[] numbers = new int[1000]; for (int i = 0; i < numbers.length; i++) { numbers[i] = i + 1; // 1, 2, ..., 1000 } long[] partial = new long[2]; // each thread writes only its own slot int mid = numbers.length / 2; Thread first = new Thread(() -> { for (int i = 0; i < mid; i++) partial[0] += numbers[i]; }); Thread second = new Thread(() -> { for (int i = mid; i < numbers.length; i++) partial[1] += numbers[i]; }); first.start(); second.start(); first.join(); // without these two joins, main could read second.join(); // partial[] before the threads have finished System.out.println("First half sum: " + partial[0]); System.out.println("Second half sum: " + partial[1]); System.out.println("Total: " + (partial[0] + partial[1])); } }

Output

First half sum: 125250 Second half sum: 375250 Total: 500500

Core Logic

Each thread owns one slot of partial, so they never write to the same place, and join() marks the point where main may safely read both slots.

How It Works
  1. 1The array is filled with 1 to 1000 and split at mid = 500.
  2. 2The first thread sums indexes 0–499 into partial[0]; the second sums 500–999 into partial[1].
  3. 3Both threads are started before either is joined, so they run at the same time.
  4. 4After both join() calls, main prints the partial sums and their total.
1 + … + 500 = 125250 and 501 + … + 1000 = 375250, which add up to 500500 (= 1000 × 1001 / 2).
💡

Key Point: Starting and immediately joining each thread in turn would make them run one after another — start all threads first, then join them.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

Why: Every number is still added exactly once in total — the two threads just split that work between them — and each thread stores a single running sum.

Key Concepts

join()lambda Runnableshared arrayhappens-before

Interview Questions

What does join(millis) do?

It waits at most the given time. Afterwards the thread may still be running, so check isAlive() if you need to know.

What's an alternative to joining many threads?

A CountDownLatch: each worker counts down when done, and the main thread calls await() once instead of joining each thread.

Learn the Concept

Related Programs