Sub topic 3
Waiting, Sleeping, and Interrupting Threads
In the last chapter you created a thread and started it. Starting a thread is only the beginning. Real programs also need to make one thread wait for another, pause a thread for a while, and ask a thread to stop early.
This chapter covers four tools for that:
startbegins a thread's work.joinmakes one thread wait until another thread finishes.sleeppauses the current thread for a set time.interruptpolitely asks a thread to stop what it is doing.
You will also learn the thread lifecycle. The lifecycle is the set of stages a thread passes through, from creation to finish.
The Thread Lifecycle
Every Java thread is in exactly one state at any moment. A state is a label that says what the thread is doing right now. Java defines these states in the Thread.State enum. An enum is a fixed list of named values.
| State | What it means |
|---|---|
| `NEW` | The thread object exists, but `start` has not been called yet. |
| `RUNNABLE` | The thread is running, or it is ready to run when the CPU is free. |
| `BLOCKED` | The thread is waiting to get a lock (you will meet locks in a later chapter). |
| `WAITING` | The thread is waiting with no time limit, for example inside `join()`. |
| `TIMED_WAITING` | The thread is waiting with a time limit, for example inside `sleep(500)`. |
| `TERMINATED` | The thread has finished its work. It cannot be started again. |
Seeing the states yourself
The method getState() returns a thread's current state. This program prints the state at three points.
public class StateDemo {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
System.out.println("Before start: " + t.getState());
t.start();
Thread.sleep(100);
System.out.println("While sleeping: " + t.getState());
t.join();
System.out.println("After join: " + t.getState());
}
}Typical output:
Before start: NEW
While sleeping: TIMED_WAITING
After join: TERMINATEDThe middle line almost always says TIMED_WAITING, because the worker sleeps for 300 ms and main checks after 100 ms. On a very busy computer the timing can shift, so you may rarely see RUNNABLE there. Timing in threaded programs is never fully guaranteed.
start: Begin the Work
You already used start in the previous chapter. Two rules are worth repeating, because beginners often break them.
sleep: Pause for a While
Thread.sleep(ms) pauses the current thread for about that many milliseconds. A millisecond is one thousandth of a second. While it sleeps, the thread is in the TIMED_WAITING state and uses no CPU time.
sleep is a static method. It always pauses the thread that calls it. Writing otherThread.sleep(1000) still pauses your thread, not otherThread. That code is legal, but it misleads readers, so always write Thread.sleep(...).
sleep can throw InterruptedException. This is a checked exception, which means the compiler forces you to handle it. Inside main you can add throws InterruptedException. Inside a Runnable lambda you cannot, because Runnable.run() declares no checked exceptions. There you must use try/catch.
join: Wait for Another Thread to Finish
worker.join() makes the calling thread wait until worker reaches TERMINATED. Without join, main might print its final message, or use a result, before the worker is done.
public class SleepJoinDemo {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
for (int i = 1; i <= 3; i++) {
System.out.println("Worker step " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}, "worker");
worker.start();
System.out.println("Main waits for worker...");
worker.join();
System.out.println("Worker finished. Main continues.");
}
}Output:
Main waits for worker...
Worker step 1
Worker step 2
Worker step 3
Worker finished. Main continues.The first two lines may swap places, because both threads start printing at nearly the same time. The last line always comes last, because join holds main back until the worker ends.
join with a time limit
Sometimes you do not want to wait forever. join(ms) waits at most that many milliseconds. It does not tell you whether the thread finished, so check with isAlive(). isAlive() returns true if the thread has started and not yet terminated.
public class JoinTimeoutDemo {
public static void main(String[] args) throws InterruptedException {
Thread slow = new Thread(() -> {
try {
Thread.sleep(5_000);
} catch (InterruptedException e) {
System.out.println("Slow task was told to stop.");
}
});
slow.start();
slow.join(1_000);
if (slow.isAlive()) {
System.out.println("Still running after 1 second. Giving up.");
slow.interrupt();
slow.join();
}
System.out.println("Main done");
}
}Output:
Still running after 1 second. Giving up.
Slow task was told to stop.
Main doneThis program combines all three tools: it waits with a limit, asks the thread to stop, then waits for it to actually finish.
interrupt: Asking a Thread to Stop
Java has no safe way to force-kill a thread. The old Thread.stop() method was unsafe and has been removed in recent Java versions. Java uses interruption instead. Interruption is a polite request: one thread sets a flag on another thread, and the other thread decides how to react.
Each thread has an interrupt flag, a true/false value. Calling t.interrupt() affects t in one of two ways:
- If
tis blocked insleep,join, or a similar waiting method, it wakes up right away and that method throwsInterruptedException. The flag is cleared (set back to false) when the exception is thrown. - If
tis busy running normal code, nothing visible happens. The flag is simply set to true.tmust check the flag itself.
Case 1: interrupting a sleeping thread
public class InterruptDemo {
public static void main(String[] args) throws InterruptedException {
Thread sleeper = new Thread(() -> {
try {
System.out.println("Sleeping for 10 seconds...");
Thread.sleep(10_000);
System.out.println("Woke up normally");
} catch (InterruptedException e) {
System.out.println("Interrupted! Stopping early.");
}
});
sleeper.start();
Thread.sleep(1_000);
sleeper.interrupt();
sleeper.join();
System.out.println("Main done");
}
}The program ends after about 1 second instead of 10. "Woke up normally" is never printed.
Case 2: interrupting a busy thread
A thread doing pure calculation never calls sleep, so no exception wakes it. It has to check its own flag with Thread.currentThread().isInterrupted().
public class BusyWorkerDemo {
public static void main(String[] args) throws InterruptedException {
Thread counter = new Thread(() -> {
long count = 0;
while (!Thread.currentThread().isInterrupted()) {
count++;
}
System.out.println("Stopped after counting to " + count);
});
counter.start();
Thread.sleep(200);
counter.interrupt();
counter.join();
}
}If you remove the isInterrupted() check and write while (true), the interrupt does nothing. The program then never ends, and join waits forever.
Handling InterruptedException Correctly
The most common mistake with interruption is to catch the exception and do nothing:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// ignored: BAD
}Remember that the flag is cleared when the exception is thrown. If you ignore the exception, the stop request is lost. Code further up, such as a loop that checks isInterrupted(), will never learn that someone asked the thread to stop.
You have two good choices:
| Situation | What to do |
|---|---|
| Your method can declare `throws InterruptedException` | Let the exception pass up to the caller. |
| You cannot rethrow it (for example inside `Runnable.run`) | Call `Thread.currentThread().interrupt()` to set the flag again, then stop or return. |
The second choice is called restoring the interrupt. It looks like this:
public class RestoreDemo {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Working...");
try {
Thread.sleep(300);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println("Worker saw the interrupt and stopped.");
});
worker.start();
Thread.sleep(1_000);
worker.interrupt();
worker.join();
}
}The catch block sets the flag again. The while condition then sees it and the loop ends. Delete the line inside catch and the loop runs forever, because the cleared flag is never seen. You will use this same pattern later in the tutorial when shutting down an ExecutorService.
Common Mistakes at a Glance
| Mistake | What happens | Fix |
|---|---|---|
| Calling `run()` instead of `start()` | No new thread; code runs on the caller | Call `start()` |
| Calling `start()` twice | `IllegalThreadStateException` | Create a new `Thread` |
| Forgetting `join()` | Main uses results before the worker is done | Call `join()` before using results |
| Using `sleep` to "wait for" another thread | Works only if you guess the timing right | Use `join()` |
| Empty `catch (InterruptedException e)` | Stop request is lost | Rethrow, or restore the interrupt |
| Busy loop that never checks the flag | `interrupt()` has no effect | Check `isInterrupted()` in the loop |
Exercise
A worker thread is in the middle of Thread.sleep(5000) when main calls worker.interrupt(). What happens inside the worker, and what is the value of its interrupt flag right after the exception is thrown?
Show answer
The sleep ends at once and throws InterruptedException in the worker. When the exception is thrown, the interrupt flag is cleared, so it is false. That is why the catch block should call Thread.currentThread().interrupt() if it cannot rethrow the exception.
Exercise
What does this code print, and why? Thread t = new Thread(() -> System.out.println("hi")); System.out.println(t.getState()); t.start(); t.join(); System.out.println(t.getState()); t.start();
Show answer
It prints NEW, then hi, then TERMINATED, and then throws IllegalThreadStateException. A thread is NEW before start, TERMINATED after its run method ends, and a Thread object can never be started a second time.
Exercise
You want main to wait at most 2 seconds for a download thread, and stop the download if it is not done by then. Which methods do you call, and in what order?
Show answer
Call download.join(2000) to wait up to 2 seconds. Then check download.isAlive(). If it returns true, call download.interrupt() to ask it to stop, then download.join() to wait until it has actually finished. The download code must respond to the interrupt, either by catching InterruptedException or by checking isInterrupted().
Exercise
Why is it misleading to write worker.sleep(1000) when you want to pause the worker thread?
Show answer
sleep is a static method that always pauses the thread that calls it. worker.sleep(1000) pauses the current thread, such as main, not worker. Always write Thread.sleep(...) so the code says what it really does.