Threads ·
‹ Previous Next ›
⏱ 5 min read Modified: 2026-11-22

Thread.join() and isAlive() in Java

Thread.join() is an instance (non-static) method of java.lang.Thread: calling t.join() pauses the current thread until thread t finishes its work. The method throws the checked InterruptedException. The typical use case is waiting for the result of some background work:

Thread worker = new Thread(() -> System.out.println("Computing..."));
worker.start();
worker.join(); // main waits until worker terminates
System.out.println("worker done");

The order of start() and join() matters here. Swap the two lines and call worker.join() before worker.start(), and the method returns instantly: a thread that hasn't been started isn't alive, so there is nothing to wait for. The code compiles, but no waiting happens (see Tricky cases).

join() Overloads: join(millis), join(Duration)

Thread.join() has four overloads: join() waits with no limit, join(long millis) and join(long millis, int nanos) wait no longer than the given time, and join(Duration), added in Java 19, also returns a boolean telling you whether the thread terminated. All four throw InterruptedException.

Call What it does Edge cases
join() Waits for the thread to terminate, with no time limit Same as join(0); if the thread hasn't started or has already finished, returns immediately
join(long millis) Waits at most millis milliseconds join(0) means wait forever, not "don't wait"; a negative value → IllegalArgumentException
join(long millis, int nanos) Milliseconds plus nanoseconds nanos outside 0–999999 → IllegalArgumentException; no real nanosecond precision
boolean join(Duration duration) Waits at most duration (Java 19+); true means the thread terminated Thread not started → IllegalThreadStateException; with a zero or negative duration it doesn't wait, it only checks whether the thread has terminated

The timed overloads wait at most the given time: if the thread finishes earlier, join returns right away. The precision of the wait itself depends on the OS and the system timer, so Java doesn't guarantee that the current thread will wait exactly the time you specified.

Thread.join() Example: Thread A Finishes Before B and C Start

In this example three threads, A, B and C, each print ten lines with a 500 ms pause. The main thread starts A and calls a.join(), so B and C start only after A has completely finished. B and C don't wait for each other, and their output is interleaved.

public class JoinThread extends Thread {
    public JoinThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        String currentThreadName = Thread.currentThread().getName();
        for (int i = 0; i < 10; i++) {
            System.out.println(currentThreadName + " is running!" + i);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // restore the flag
                return;                             // and stop working
            }
        }
        System.out.println(currentThreadName + " completed");
    }
}
public class JoinExample {
    public static void main(String[] args) throws InterruptedException {
        JoinThread a = new JoinThread("A");
        JoinThread b = new JoinThread("B");
        JoinThread c = new JoinThread("C");

        a.start();
        a.join(); // main waits until A prints "A completed"
        b.start();
        c.start();
    }
}

One possible output (some lines omitted):

A is running!0
A is running!1
...
A is running!9
A completed
B is running!0
C is running!0
C is running!1
B is running!1
...
B is running!9
C is running!9
C completed
B completed

The block of A lines always comes first and ends with "A completed" — that's what join() guarantees. The order of B and C lines changes from run to run. Remove a.join(), and all three threads interleave from the very first second.

Timed join() Doesn't Guarantee the Thread Has Finished

After join(1000) returns, the thread may still be alive: the method simply stopped waiting. There are two ways to find out how a timed join ended — check t.isAlive() or, since Java 19, use the result of join(Duration).

import java.time.Duration;

public class TimedJoinExample {
    public static void main(String[] args) throws InterruptedException {
        Thread slow = new Thread(() -> {
            try {
                Thread.sleep(3000); // runs for ~3 seconds
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        slow.start();

        slow.join(1000);
        System.out.println("After join(1000): isAlive = " + slow.isAlive());

        boolean finished = slow.join(Duration.ofSeconds(1)); // Java 19+
        System.out.println("join(Duration) returned " + finished);

        slow.join();
        System.out.println("After join(): isAlive = " + slow.isAlive());
    }
}
After join(1000): isAlive = true
join(Duration) returned false
After join(): isAlive = false

The first two checks fire after one and two seconds, while the thread runs for three, so both say "still alive". Code that reads a thread's results right after join(timeout) without such a check will get incomplete data.

Thread.isAlive(): Is the Thread Still Running

The isAlive() method returns true if the thread has been started and hasn't finished yet. A false means one of two things: the thread was created but start() was never called, or the thread has already completed.

If a thread is created but not started, isAlive() in Java returns false. As soon as start() is called, the thread is considered alive, and isAlive() returns true. Once the thread finishes, the method returns false again.

public class IsAliveExample {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        System.out.println("Before starting: " + thread.isAlive());
        thread.start();
        System.out.println("After starting: " + thread.isAlive());
        thread.join();
        System.out.println("After thread completed: " + thread.isAlive());
    }
}
Before starting: false
After starting: true
After thread completed: false

Keep in mind that isAlive() can't tell "not started yet" from "already done". If you need that distinction, use getState(): it returns Thread.State.NEW for a thread that hasn't been started and Thread.State.TERMINATED for one that has finished.

isAlive() right after start()

In IsAliveExample the thread sleeps for 500 ms, so "After starting: true" is printed reliably. If the task is tiny (a single line of output), the thread may finish before main reaches the check, and you'll see false. The result of isAlive() is a snapshot at the moment of the call; a microsecond later it may already be different.

What Happens to the Waiting Thread

A thread that calls t.join() goes into the WAITING state, or TIMED_WAITING with join(millis), and uses no CPU. It resumes when t terminates, when the timeout expires, or when another thread calls interrupt() on the waiting thread. WAITING is waiting without a time limit; TIMED_WAITING is waiting with one.

The wait in join() can be interrupted: the method then throws InterruptedException and clears the interrupt flag. The handling rules are the same as for sleep() — don't swallow the exception, restore the flag or rethrow it. A detailed walkthrough with an example is in Thread.sleep(): InterruptedException.

join() has a property that people often forget: it gives a memory visibility guarantee. Under the Java Memory Model (JLS 17.4.5), all actions in thread t happen-before another thread successfully returns from t.join(). So after join() you can read fields written by t without volatile or synchronized:

public class JoinVisibility {
    static int result; // not volatile

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> result = 42);
        t.start();
        t.join();
        System.out.println(result); // Output: 42 - guaranteed
    }
}

The guarantee holds only once join() has actually waited for termination. If join(1000) returned on timeout while the thread is still running, reading its data without synchronization is not safe.

Tricky Cases with join()

Interviewers asking about join() usually go for three questions: what happens if you call it before start(), what join(0) means, and what a thread does if it calls join() on itself. The answers: it returns immediately, it waits forever, and it hangs forever.

What does this code print?

public class SelfJoin {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("Waiting for myself...");
        Thread.currentThread().join();
        System.out.println("Never gets here");
    }
}
Waiting for myself...

The program prints one line and hangs until you kill it. The main thread waits for the main thread to terminate, and it can't terminate because it's waiting. No exception, no compiler warning.

The same thing happens when two threads call join() on each other: each waits for the other, and both hang forever. This is a special case of a circular wait — see Deadlock in Java.

Here's what a join before start looks like:

Thread t = new Thread(() -> System.out.println("working"));
t.join();   // thread not started yet - returns at once, no waiting
t.start();
System.out.println("main continues");

Here main doesn't wait for t, and "main continues" is usually printed before "working", although the order isn't guaranteed. join(Duration) won't let this mistake slip through: for a thread that hasn't been started it throws IllegalThreadStateException.

join() Instead of Polling isAlive() in a Loop

To wait for a thread to finish, use join(), not a loop over isAlive(). A loop like while (t.isAlive()) {} spins idly and keeps a whole CPU core busy (busy-waiting), while join() puts the waiting thread to sleep until t terminates and also gives you the visibility guarantee.

// Bad: a CPU core is burned on empty checks
while (t.isAlive()) {
}

// Good: the thread sleeps until t terminates
t.join();

Polling with Thread.sleep(100) barely loads the CPU, but it reacts up to 100 ms late and gains nothing over join(). Polling isAlive() makes sense only where you can't block: for example, in a UI render loop that shows "still computing" once per frame.

When there are many threads, or you aren't working with Thread directly, java.util.concurrent has better tools: CountDownLatch lets you wait for N events without tying them to the termination of specific threads, and ExecutorService.invokeAll() runs a batch of tasks in a pool and returns once all of them are done.

join() with Virtual Threads

With virtual threads (Java 21+), join() works the same way as with platform threads, and you need it even more often: virtual threads are always daemon threads, and the JVM doesn't wait for them to finish. Without join(), main may exit before the virtual thread gets to do anything.

public class VirtualJoin {
    public static void main(String[] args) throws InterruptedException {
        Thread vt = Thread.ofVirtual().start(() ->
                System.out.println("virtual: " + Thread.currentThread().isVirtual()));
        vt.join(); // without this line the output may never appear
    }
}
virtual: true

When a virtual thread itself calls join(), it is unmounted from its carrier thread for the duration of the wait, and the carrier goes on running other virtual threads. That's why thousands of virtual threads waiting on each other through join() don't tie up thousands of OS threads.

Frequently Asked Questions

What happens if you call join() inside a synchronized block?

The waiting thread keeps holding the monitor for the entire wait. If thread t tries to enter synchronized on the same object, it blocks, join() never sees it terminate, and both threads hang. Call join() outside of locks. Holding a lock while waiting is one of the classic ingredients of a deadlock in Java.

How do I wait for multiple threads to finish?

Start all the threads first, then call join() on each of them in a loop. The total wait equals the time of the longest thread, not the sum: while main waits for the first thread, the others keep running. If you call start() and join() in the same loop, the threads run strictly one after another, and the point of multithreading is lost.

Can I call join() on a thread that has already finished?

Yes, as many times as you like: the method returns immediately, with no exception. Unlike start(), which throws IllegalThreadStateException for a finished thread, join() only checks whether the thread is alive.

What is the difference between join() and sleep()?

sleep() is a static method that pauses for a fixed time regardless of other threads. join() is called on a specific thread and waits for an event — its termination — so it may return after a millisecond or after an hour. More on pauses in Thread.sleep() in Java.

Comments

Please log in or register to have a possibility to add comment.