Skip to lesson

Pause and wait: sleep and join

The main thread starts a worker to total the day's orders and then prints the total. Printed too early, it shows zero. How should it wait, and why is just pausing not the answer?

Thread.sleep and the checked InterruptedException

join makes the current thread wait until another thread has finished, so its results are ready to use.

Thread.sleep(ms) pauses the current thread for about ms milliseconds, often a little longer, depending on the system timer. While it sleeps it uses no CPU, and other threads keep running.

Example 1 · A Tatkal countdown with sleep

CountdownDemo.javaJava
public class CountdownDemo {    public static void main(String[] args) throws InterruptedException {        System.out.println("Tatkal booking opens in...");        for (int s = 3; s >= 1; s--) {            System.out.println(s);            Thread.sleep(100);        // a short pause; a real countdown would use 1000        }        System.out.println("Booking is open");    }}
Output
Tatkal booking opens in...
3
2
1
Booking is open

What this code does

  • Thread.sleep(100) pauses main for about 100 ms between lines, so the output appears slowly, but the text is always the same.
  • main declares throws InterruptedException because sleep can throw that checked exception.

Example 2 · sleep inside a lambda needs try/catch

SleepInRunDemo.javaJava
public class SleepInRunDemo {    public static void main(String[] args) throws InterruptedException {        Thread reminder = new Thread(() -> {            System.out.println("Reminder: hostel fee due tomorrow");            Thread.sleep(100);            System.out.println("Reminder: hostel fee due today");        }, "reminder");        reminder.start();        reminder.join();    }}
Sample compiler output
SleepInRunDemo.java:5: error: unreported exception InterruptedException; must be caught or declared to be thrown
            Thread.sleep(100);
                        ^
1 error

What this code does

  • The lambda is the body of Runnable.run(), which declares no checked exceptions. throws InterruptedException on main does not help, because the lambda is a separate method.
  • Fix: wrap the call in try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }. The return ends the task, since someone asked it to stop.

sleep can throw InterruptedException, a checked exception: it means another thread asked this one to stop waiting. So you must handle it. In main you can declare throws InterruptedException. Inside run() or a lambda you cannot, because Runnable.run() declares no checked exceptions, so you need try/catch there. In the catch, call Thread.currentThread().interrupt(); for now. The lesson Stop a thread politely with interrupt explains what it does and why it matters.

sleep is a static method. worker.sleep(500) still pauses the thread that runs the line, not worker.

join() to wait for a thread to finish

join() makes the calling thread wait until the target thread has finished. main calling t.join() simply stops at that line until t's run() has returned.

Example 3 · join: wait for every evaluator

JoinDemo.javaJava
class Evaluator implements Runnable {    private final String subject;    private final int[] marks;    private final long workMs;    private int highest;
    Evaluator(String subject, int[] marks, long workMs) {        this.subject = subject;        this.marks = marks;        this.workMs = workMs;    }
    @Override    public void run() {        try {            Thread.sleep(workMs);     // pretend evaluation takes time        } catch (InterruptedException e) {            Thread.currentThread().interrupt();            return;        }        for (int m : marks) {            highest = Math.max(highest, m);        }    }
    String report() {        return subject + " highest: " + highest;    }}
public class JoinDemo {    public static void main(String[] args) throws InterruptedException {        Evaluator maths = new Evaluator("Maths", new int[] {67, 92, 85}, 150);        Evaluator physics = new Evaluator("Physics", new int[] {71, 64, 88}, 50);        Evaluator chemistry = new Evaluator("Chemistry", new int[] {90, 77, 81}, 100);
        Thread[] threads = {            new Thread(maths, "maths"), new Thread(physics, "physics"), new Thread(chemistry, "chemistry")        };        for (Thread t : threads) {            t.start();        }        for (Thread t : threads) {            t.join();                 // wait for each one to finish        }
        System.out.println(maths.report());        System.out.println(physics.report());        System.out.println(chemistry.report());        System.out.println("All results ready");    }}
Output
Maths highest: 92
Physics highest: 88
Chemistry highest: 90
All results ready

What this code does

  • All three evaluators run at the same time. main joins them in a fixed order; when physics finishes first, its join() simply returns at once.
  • The total wait is about 150 ms, the time of the slowest evaluator, not 300 ms. The reports are read only after every join(), so they are complete.

To wait for several threads, start them all first and then join them one by one. The total wait is about as long as the slowest thread, not the sum of all of them, because they ran at the same time. join() also throws the checked InterruptedException.

Trace the code

Follow main while it waits for a worker

Press Next to see which thread runs each line and when main waits.

public class JoinTrace {
static int total = 0;
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
for (int i = 1; i <= 3; i++) {
total += i;
}
});
worker.start();
worker.join();
System.out.println("Total: " + total);
}
}

Variables

total
0

Output

(nothing printed yet)

Line 5main creates the Thread object. Nothing runs on the new thread yet.

Step 1 of 8
Joining a thread that has already finished, or was never started, returns at once.

join with a timeout

join(ms) waits at most ms milliseconds. It returns when the thread finishes or when the time is up, whichever comes first, and it does not tell you which one happened.

Example 4 · join with a timeout and isAlive

JoinTimeoutDemo.javaJava
public class JoinTimeoutDemo {    public static void main(String[] args) throws InterruptedException {        Thread gateway = new Thread(() -> {            try {                Thread.sleep(200);    // the bank takes 200 ms to reply            } catch (InterruptedException e) {                Thread.currentThread().interrupt();                return;            }            System.out.println("gateway: payment of Rs 499 confirmed");        }, "gateway");
        gateway.start();        gateway.join(50);             // wait at most 50 ms        if (gateway.isAlive()) {            System.out.println("main: still processing, showing a spinner");        }
        gateway.join();               // now wait until it is really done        System.out.println("main: gateway alive = " + gateway.isAlive());    }}
Output
main: still processing, showing a spinner
gateway: payment of Rs 499 confirmed
main: gateway alive = false

What this code does

  • join(50) returned after about 50 ms although the gateway needs 200 ms. It does not say why it returned, so isAlive() checks: true means the wait timed out.
  • The plain join() afterwards waits for the real finish, and isAlive() is then false. A real app might instead give up after a few timeouts and show an error.

So check isAlive() straight after it: true means the thread is still running and the wait timed out. This is useful when you would rather show "still processing" than freeze, such as waiting for a payment gateway or an OTP.

Reading results only after join

A worker's result is safe to read only after join() returns. Before that, the worker may still be writing it.

Example 5 · sleep is not a way to wait

SleepIsNotWaitDemo.javaJava
public class SleepIsNotWaitDemo {    static int[] seatsLeft = {0};
    static Thread startCounter() {        Thread counter = new Thread(() -> {            try {                Thread.sleep(150);    // the server is slow today            } catch (InterruptedException e) {                Thread.currentThread().interrupt();                return;            }            seatsLeft[0] = 42;        }, "seat-counter");        counter.start();        return counter;    }
    public static void main(String[] args) throws InterruptedException {        startCounter();        Thread.sleep(50);             // WRONG: "50 ms is surely enough"        System.out.println("After sleep(50): seats left = " + seatsLeft[0]);
        seatsLeft[0] = 0;        Thread counter = startCounter();        counter.join();               // RIGHT: wait until it has finished        System.out.println("After join():    seats left = " + seatsLeft[0]);    }}
Sample output
After sleep(50): seats left = 0
After join():    seats left = 42

What this code does

  • The guessed 50 ms was too short, so main read the old value 0. With a faster server the guess might work, which makes this bug come and go. (The first counter may still be running when main ends; that is harmless here.)
  • join() waits exactly as long as needed and guarantees main sees the value the counter wrote. Times depend on the computer, so this output is a sample.

After join(), Java guarantees that everything the finished thread wrote is visible to the thread that joined. This is one of Java's happens-before rules, covered in the Visibility and volatile module.

sleep is not a way to wait for another thread. Sleeping "long enough" either wastes time when the worker is fast or is too short when the computer is busy, and then you read a half-done or empty result. sleep also gives none of the visibility guarantee that join gives.

Next step

Check your understanding

12 quick questions