Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Thread.join()

Waits for a thread to finish.

Available since: Java 1.0

Syntax

public final void join() throws InterruptedException
public final boolean join(Duration duration) throws InterruptedException

Parameters

ParameterTypeDescription
durationDurationOptional wait limit (Java 19).

Examples

Without join() the result may not be ready yet:

void main() throws InterruptedException {
    List<String> log = Collections.synchronizedList(new ArrayList<>());
    Thread t = new Thread(() -> {
        try { Thread.sleep(200); } catch (InterruptedException e) { return; }
        log.add("work finished");
    });
    t.start();
    IO.println("before join: " + log);
    t.join();
    IO.println("after join: " + log);
}

Output:

before join: []
after join: [work finished]

Notes

The method blocks the current thread until the other one finishes. It declares the checked InterruptedException, so main either declares throws InterruptedException or wraps the call in try. The Duration version waits no longer than the given time.

See also

  • Thread.start() — Starts a thread: its code begins running in parallel with the caller.
  • Thread.sleep() — Pauses the current thread for a given time.
  • CountDownLatch — A counter that lets a thread wait until others have performed N actions.
  • Future.get() — Waits for a task to finish and returns its result.

In the tutorial

  • Threads — Threads in Java — the Thread class, starting with start, waiting with join, Thread.sleep, thread names and unpredictable execution order.

Thanks for reading!

Donate to the site — we work hard for you.