Sub topic 3
Waiting, Sleeping, and Interrupting Threads
Starting a thread is only the first step. Your program often needs to wait for a thread to finish, pause a thread for a while, or ask a thread to stop early. Java gives you four tools for this: start, join, sleep, and interrupt.
The Life of a Thread
Every thread moves through a few states during its life. A state is a label that says what the thread is doing right now. You can read it with getState().
| State | What it means |
|---|---|
| `NEW` | The thread object exists, but `start` has not been called. |
| `RUNNABLE` | The thread is running or ready to run. |
| `TIMED_WAITING` | The thread is paused for a set time, for example inside `sleep`. |
| `WAITING` | The thread is paused with no time limit, for example inside `join`. |
| `TERMINATED` | The thread has finished its work. |
Waiting with join
join is a method that makes the current thread wait until another thread finishes. If main calls worker.join(), then main stops at that line until worker reaches TERMINATED.
Without join, main might print its results before the worker has done its job. You can also give a limit, like join(2000), to wait at most two seconds.
Pausing with sleep
Thread.sleep(ms) pauses the current thread for about that many milliseconds. A millisecond is one thousandth of a second. sleep is a static method, so it always pauses the thread that calls it, never some other thread.
sleep and join can both throw InterruptedException. This is a checked exception, so you must catch it or declare it with throws.
Asking a Thread to Stop with interrupt
interrupt is a polite request to stop. It does not kill the thread. It sets a flag on the thread called the interrupt flag. If the thread is sleeping or joining, Java wakes it at once and throws InterruptedException inside it. The thread then decides how to react.
Here is a full example. A worker tries to sleep for five seconds, but main interrupts it after one second.
public class InterruptDemo {
public static void main(String[] args) throws InterruptedException {
Thread sleeper = new Thread(() -> {
try {
System.out.println("Sleeping for 5 seconds...");
Thread.sleep(5000);
System.out.println("Woke up normally");
} catch (InterruptedException e) {
System.out.println("Interrupted! Stopping early.");
}
}, "sleeper");
System.out.println("State before start: " + sleeper.getState());
sleeper.start();
Thread.sleep(1000);
System.out.println("State while sleeping: " + sleeper.getState());
sleeper.interrupt();
sleeper.join();
System.out.println("State after join: " + sleeper.getState());
System.out.println("Main thread done");
}
}Output:
State before start: NEW
Sleeping for 5 seconds...
State while sleeping: TIMED_WAITING
Interrupted! Stopping early.
State after join: TERMINATED
Main thread doneThe program ends after about one second instead of five.
Checking the Flag in a Loop
A thread that is busy working, not sleeping, gets no exception. It has to check the flag itself with Thread.currentThread().isInterrupted().
public class LoopInterruptDemo {
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(500);
counter.interrupt();
counter.join();
}
}Exercise
In InterruptDemo, what would happen if you removed the line sleeper.interrupt()?
Show answer
The sleeper thread would sleep the full five seconds and print "Woke up normally". The main thread would wait at sleeper.join() until then, so the program would take about five seconds instead of one.
Exercise
A thread calls Thread.sleep(3000) and another thread calls interrupt() on it one second later. What happens inside the sleeping thread?
Show answer
It wakes up right away. Thread.sleep throws InterruptedException, and the interrupt flag is cleared. The thread's catch block then decides what to do.