Wait for Threads Using join() in Java
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.
Java Program
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
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.
- 1The array is filled with 1 to 1000 and split at
mid = 500. - 2The first thread sums indexes 0–499 into
partial[0]; the second sums 500–999 intopartial[1]. - 3Both threads are started before either is joined, so they run at the same time.
- 4After both
join()calls, main prints the partial sums and their total.
Key Point: Starting and immediately joining each thread in turn would make them run one after another — start all threads first, then join them.
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
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.