Java Thread Join

Su Suriya Ravichandran Updated 18 Nov 2026
13 min read ·Lesson 187 of 306

The Java thread join() method makes one thread wait until another thread has finished. When main calls worker.join(), main pauses on that line and continues only after worker has terminated.

You use join() whenever the next step depends on the result of other threads: open a file after it has downloaded, add up partial results after every worker is done, or shut down cleanly after background tasks complete.


Java Thread join() Syntax

join() is an instance method: you call it on the thread you want to wait for. The calling thread is the one that waits.

thread.join()                     // wait until thread terminates, no time limit
thread.join(long millis)          // wait at most millis milliseconds
thread.join(long millis, int nanos)
boolean done = thread.join(Duration timeout)   // Java 19+, returns true if it finished
MethodReturnsWaiting state of the caller
join()voidWAITING
join(millis) / join(millis, nanos)voidTIMED_WAITING
join(Duration)boolean: true if the thread terminatedTIMED_WAITING

Every form throws InterruptedException if the waiting thread is interrupted. join(0) means "wait forever", the same as join().


The Problem join() Solves

Without join(), main keeps running while the worker is still busy. Here main tries to use a file that has not been downloaded yet.

public class WithoutJoin {
    public static void main(String[] args) {
        Thread downloader = new Thread(() -> {
            try {
                Thread.sleep(500); // simulate a slow download
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            System.out.println("downloader: file downloaded");
        }, "downloader");

        downloader.start();
        System.out.println("main: opening the file now"); // too early!
    }
}

Output:

main: opening the file now
downloader: file downloaded

How it works:

  • downloader.start() returns immediately; the download happens in the background.
  • main goes straight to its next line, so it "opens" the file 500 ms too early.

How to Use Java Thread join()

Adding one join() call fixes the order: main waits on that line until downloader is done.

public class WithJoin {
    public static void main(String[] args) throws InterruptedException {
        Thread downloader = new Thread(() -> {
            try {
                Thread.sleep(500); // simulate a slow download
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            System.out.println("downloader: file downloaded");
        }, "downloader");

        downloader.start();
        System.out.println("main: waiting for the download...");
        downloader.join(); // main pauses here until downloader has finished
        System.out.println("main: opening the file now");
        System.out.println("main: downloader alive? " + downloader.isAlive());
    }
}

Output:

main: waiting for the download...
downloader: file downloaded
main: opening the file now
main: downloader alive? false

How it works:

  • downloader.join() blocks main until downloader's run() method returns.
  • After join() returns, isAlive() is false and the thread is in the TERMINATED state, as described in Java Thread States.

Joining Multiple Threads in Java

To run several tasks in parallel and wait for all of them, start every thread first, then join them one by one. Joining inside the start loop would run them one after another.

import java.util.ArrayList;
import java.util.List;

public class JoinMany {
    public static void main(String[] args) throws InterruptedException {
        String[] reports = {"sales", "inventory", "customers"};
        int[] durations = {700, 300, 500};
        List<Thread> workers = new ArrayList<>();

        long start = System.nanoTime();
        for (int i = 0; i < reports.length; i++) {
            String report = reports[i];
            int millis = durations[i];
            Thread worker = new Thread(() -> {
                try {
                    Thread.sleep(millis); // simulate building the report
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                System.out.println(report + " report ready (" + millis + " ms)");
            }, report + "-worker");
            workers.add(worker);
            worker.start(); // start ALL threads first...
        }

        for (Thread worker : workers) {
            worker.join(); // ...then wait for each one
        }

        long totalMillis = (System.nanoTime() - start) / 1_000_000;
        System.out.println("All reports ready. Took under 1000 ms: " + (totalMillis < 1000));
    }
}

Output:

inventory report ready (300 ms)
customers report ready (500 ms)
sales report ready (700 ms)
All reports ready. Took under 1000 ms: true

How it works:

  • All three workers start immediately and sleep at the same time, so the total time is about 700 ms (the slowest one), not 1500 ms (the sum).
  • The second loop joins each thread in list order. Joining sales first takes 700 ms; by then the other two have already finished, so their join() calls return at once.
  • The order in which you join does not change the total time.

Collecting Results from Threads with join()

join() also guarantees visibility: everything a thread wrote before it ended is visible to the thread that joined it. That makes it safe to read results after join() returns.

public class JoinSum {
    // Each worker stores its result in its own slot, so no locking is needed
    static long[] partialSums = new long[4];

    public static void main(String[] args) throws InterruptedException {
        int[] numbers = new int[1_000_000];
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = i + 1; // 1, 2, 3, ..., 1,000,000
        }

        int parts = partialSums.length;
        int chunk = numbers.length / parts;
        Thread[] workers = new Thread[parts];

        for (int p = 0; p < parts; p++) {
            int index = p;
            int from = p * chunk;
            int to = (p == parts - 1) ? numbers.length : from + chunk;
            workers[p] = new Thread(() -> {
                long sum = 0;
                for (int i = from; i < to; i++) {
                    sum += numbers[i];
                }
                partialSums[index] = sum;
            });
            workers[p].start();
        }

        for (Thread worker : workers) {
            worker.join(); // after join, the worker's result is safely visible
        }

        long total = 0;
        for (int p = 0; p < parts; p++) {
            System.out.println("part " + p + ": " + partialSums[p]);
            total += partialSums[p];
        }
        System.out.println("total : " + total);
        System.out.println("check : " + (1_000_000L * 1_000_001L / 2));
    }
}

Output:

part 0: 31250125000
part 1: 93750125000
part 2: 156250125000
part 3: 218750125000
total : 500000500000
check : 500000500000

How it works:

  • The array of one million numbers is split into four chunks, and each worker adds up its own chunk.
  • Each worker writes to its own slot in partialSums, so the threads never write to the same variable.
  • After all four join() calls, main reads the four slots safely and adds them. The total matches the formula n × (n + 1) / 2.

Note: Reading a worker's result without join() (or another synchronization tool) is unsafe: main might see an old value. The rules behind this are covered in Java Synchronization.


Java Thread join() with a Timeout

join(millis) waits at most the given time. It returns void, so after it returns you check isAlive() to find out whether the thread finished or the time ran out.

public class JoinTimeout {
    public static void main(String[] args) throws InterruptedException {
        Thread slowBackup = new Thread(() -> {
            try {
                Thread.sleep(3000); // a backup that takes 3 seconds
                System.out.println("backup: finished");
            } catch (InterruptedException e) {
                System.out.println("backup: cancelled");
            }
        }, "backup");

        slowBackup.start();
        slowBackup.join(1000); // wait at most 1 second

        if (slowBackup.isAlive()) {
            System.out.println("main: backup still running after 1 s, cancelling it");
            slowBackup.interrupt();
            slowBackup.join(); // wait for it to react to the interrupt
        }
        System.out.println("main: backup alive? " + slowBackup.isAlive());
    }
}

Output:

main: backup still running after 1 s, cancelling it
backup: cancelled
main: backup alive? false

How it works:

  • slowBackup.join(1000) returns after one second, even though the backup needs three.
  • isAlive() is still true, so main interrupts the backup. Its sleep() throws InterruptedException and the thread ends.
  • A final join() without a timeout waits for the backup to finish reacting to the interrupt.

join(Duration) Returns Whether the Thread Finished

Since Java 19, join(Duration) tells you directly whether the thread terminated in time, so you do not need a separate isAlive() check.

import java.time.Duration;

public class JoinDuration {
    static Thread task(String name, long millis) {
        Thread t = new Thread(() -> {
            try {
                Thread.sleep(millis);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, name);
        t.start();
        return t;
    }

    public static void main(String[] args) throws InterruptedException {
        Thread quick = task("quick", 200);
        Thread slow = task("slow", 2000);

        // join(Duration) returns true if the thread terminated in time (Java 19+)
        boolean quickDone = quick.join(Duration.ofMillis(500));
        boolean slowDone = slow.join(Duration.ofMillis(500));

        System.out.println("quick finished within 500 ms: " + quickDone);
        System.out.println("slow finished within 500 ms : " + slowDone);

        slow.join(); // wait for the rest before exiting
    }
}

Output:

quick finished within 500 ms: true
slow finished within 500 ms : false

How it works:

  • quick sleeps 200 ms, so it finishes within the 500 ms limit and join returns true.
  • slow sleeps 2000 ms, so join gives up after 500 ms and returns false.

join() on a Thread That Was Never Started

join() waits only while the thread is alive. A thread that has not been started yet is not alive, so join() returns immediately without waiting.

public class JoinNotStarted {
    public static void main(String[] args) throws InterruptedException {
        Thread report = new Thread(() -> System.out.println("report: generated"), "report");

        long start = System.nanoTime();
        report.join(); // report was never started: join() returns at once
        long waitedMicros = (System.nanoTime() - start) / 1_000;

        System.out.println("main: join() returned, state = " + report.getState());
        System.out.println("main: waited less than 1 ms: " + (waitedMicros < 1000));

        report.start();
        report.join(); // now it really waits for the thread to finish
        System.out.println("main: state after real join = " + report.getState());
    }
}

Output:

main: join() returned, state = NEW
main: waited less than 1 ms: true
report: generated
main: state after real join = TERMINATED

How it works:

  • The first report.join() happens while report is still NEW. It returns at once and the report has not been generated.
  • After report.start(), the second join() really waits until the thread is TERMINATED.
  • Always call start() before relying on join().

Interrupting a Thread That Is Waiting in join()

A thread blocked in join() is in the WAITING state. If another thread interrupts it, join() stops waiting and throws InterruptedException. The thread it was joining keeps running.

public class JoinInterrupted {
    public static void main(String[] args) throws InterruptedException {
        Thread endless = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                Thread.onSpinWait(); // keeps running until interrupted
            }
        }, "endless");

        Thread waiter = new Thread(() -> {
            try {
                System.out.println("waiter: joining endless...");
                endless.join(); // would wait forever
            } catch (InterruptedException e) {
                System.out.println("waiter: interrupted while joining, giving up");
            }
        }, "waiter");

        endless.start();
        waiter.start();
        Thread.sleep(300);
        System.out.println("main: waiter state = " + waiter.getState());

        waiter.interrupt();   // stop waiting
        waiter.join();
        endless.interrupt();  // stop the endless thread too
        endless.join();
        System.out.println("main: both threads stopped");
    }
}

Output:

waiter: joining endless...
main: waiter state = WAITING
waiter: interrupted while joining, giving up
main: both threads stopped

How it works:

  • waiter calls endless.join(), which would never return, because endless loops until it is interrupted.
  • main interrupts waiter. Its join() throws InterruptedException, and waiter gives up.
  • Interrupting waiter does not stop endless; main has to interrupt endless separately.

Running Threads in Order with join()

Threads can join each other to build a simple chain of steps: each step waits for the one before it.

public class JoinOrder {
    public static void main(String[] args) throws InterruptedException {
        Thread validate = new Thread(() -> System.out.println("1. validate cart"));
        Thread charge = new Thread(() -> {
            try {
                validate.join(); // charge only after validation is done
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            }
            System.out.println("2. charge card");
        });
        Thread ship = new Thread(() -> {
            try {
                charge.join(); // ship only after the payment is done
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            }
            System.out.println("3. ship order");
        });

        // Start each thread before any thread that joins it
        validate.start();
        charge.start();
        ship.start();

        ship.join();
        System.out.println("order complete");
    }
}

Output:

1. validate cart
2. charge card
3. ship order
order complete

How it works:

  • charge calls validate.join() before charging, and ship calls charge.join() before shipping.
  • The threads are started in dependency order, so every thread that gets joined has already been started (see the previous section for why that matters).
  • The output order is always the same, even though three threads are involved.
join()Thread.sleep()
Waits forAnother thread to finishA fixed amount of time
Called onThe thread to wait for (t.join())The class (Thread.sleep(ms))
Ends early whenThe thread finishesNever (only on interrupt)
Use to coordinate threadsYesNo; guessing a delay is unreliable

For more on pausing a thread for a fixed time, see Java Thread Sleep.


Real-World Example: Load an Order Page from Several Services

An order page needs data from four backend services. Calling them one after another would be slow, so each call runs in its own thread. The page has a time budget of 800 ms: any service that has not answered by then is cancelled and replaced with a fallback text.

import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.Map;

public class OrderSummaryJob {
    // A worker thread that loads one piece of data and keeps the result
    static class Loader extends Thread {
        private final long delayMillis;
        private final String value;
        private String result; // written by this thread, read by main after join()

        Loader(String name, long delayMillis, String value) {
            super(name);
            this.delayMillis = delayMillis;
            this.value = value;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(delayMillis); // simulate a remote call
                result = value;
            } catch (InterruptedException e) {
                result = null; // cancelled
            }
        }

        String result() {
            return result;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Map<String, Loader> loaders = new LinkedHashMap<>();
        loaders.put("customer", new Loader("customer-service", 300, "Priya Nair (Gold member)"));
        loaders.put("items", new Loader("cart-service", 450, "3 items, Rs. 2,450"));
        loaders.put("shipping", new Loader("shipping-service", 250, "Delivery by Thursday"));
        loaders.put("offers", new Loader("offers-service", 5000, "10% off next order"));

        long start = System.nanoTime();
        loaders.values().forEach(Thread::start); // all calls run in parallel

        Duration budget = Duration.ofMillis(800); // the page must render within 800 ms
        long deadline = System.nanoTime() + budget.toNanos();

        Map<String, String> summary = new LinkedHashMap<>();
        for (Map.Entry<String, Loader> entry : loaders.entrySet()) {
            Loader loader = entry.getValue();
            long remainingNanos = Math.max(0, deadline - System.nanoTime());
            boolean finished = loader.join(Duration.ofNanos(remainingNanos));

            if (finished) {
                summary.put(entry.getKey(), loader.result());
            } else {
                loader.interrupt(); // too slow: cancel and use a fallback
                summary.put(entry.getKey(), "(not available right now)");
            }
        }

        long tookMillis = (System.nanoTime() - start) / 1_000_000;
        System.out.println("=== Order Summary ===");
        summary.forEach((section, text) -> System.out.printf("%-9s: %s%n", section, text));
        System.out.println("Rendered within budget: " + (tookMillis < 900));
    }
}

Output:

=== Order Summary ===
customer : Priya Nair (Gold member)
items    : 3 items, Rs. 2,450
shipping : Delivery by Thursday
offers   : (not available right now)
Rendered within budget: true

How it works:

  1. One thread per service. Loader extends Thread (see Java Thread Class) and stores its result in a field. All four loaders start together.
  2. One shared deadline. Instead of giving each join() a fresh 800 ms, the code computes a single deadline and passes only the remaining time to each join(Duration). The whole page therefore waits at most 800 ms in total.
  3. Using the boolean result. join(Duration) returns true for the three fast services, so their results are read safely after the join.
  4. Fallback for slow services. The offers service needs 5 seconds. Its join returns false, so the loader is interrupted and the page shows a placeholder instead of making the customer wait.
  5. Fast overall. The page is ready after about 800 ms, even though one service would have taken 5 seconds.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Thread Join and get answers drawn from it.

Signed-in readers only.