Thread lifecycle and interruption
What you will learn
A thread is an independent path of execution. A Runnable describes work; starting a Thread schedules that work on a different execution path. Joining observes completion, while interruption requests cooperative cancellation rather than forcibly terminating a worker.
- Distinguish start from a direct run call.
- Describe lifecycle states and use a bounded join.
- Handle interruption by propagating or restoring the status.
Each example is a complete Main.java file. Use a fresh lab-owned directory: javac --release 21 -proc:none Main.java, then java Main. Only finite reviewed tasks are started. Latches and barriers coordinate workers with explicit deadlines; their full APIs are covered in Chapter 32. The fixture runner also enforces a process deadline.
Start versus run
import java.time.Duration;import java.util.concurrent.*;public class Main { // Only finite tasks and timed coordination are used in these examples. static void finish(Thread thread) throws InterruptedException { try { if (!thread.join(Duration.ofSeconds(3))) { thread.interrupt(); if (!thread.join(Duration.ofSeconds(3))) throw new AssertionError("worker did not stop"); throw new AssertionError("worker timed out"); } } catch (InterruptedException e) { thread.interrupt(); throw e; } } public static void main(String[] args) throws Exception { Runnable work = () -> System.out.println(Thread.currentThread().getName()); Thread worker = new Thread(work, "catalog-worker"); worker.run(); System.out.println(worker.getState()); worker.start(); finish(worker); System.out.println(worker.getState()); }}Expected output:
mainNEWcatalog-workerTERMINATEDDirect run uses main; start uses the named worker. NEW and TERMINATED are stable at the chosen observation points.
Lifecycle and scheduling
A new Thread begins in NEW. After start, it can be RUNNABLE (eligible to run or executing), BLOCKED (waiting to enter a monitor), WAITING or TIMED_WAITING (waiting for specified operations), and finally TERMINATED. These are JVM states, not a complete OS scheduler model. A snapshot of an intermediate state can change immediately; use coordination rather than state polling. A Thread instance may be started only once. Calling run directly is a normal call on the current thread for the platform-thread example shown. Platform threads generally use OS threads; virtual threads are introduced later.
Bounded completion
The Java 19+ join(Duration) returns a boolean indicating termination and rejects an unstarted thread. join(long) instead returns void, with zero meaning unlimited; check isAlive after a timed join. A timeout is a failure to observe completion, not proof the thread failed or stopped. The helper uses a three-second deadline and an interrupt plus second bounded join on failure. Worker tasks here have finite work or timed waits; production shutdown must also handle an uncooperative worker. Do not ignore worker exceptions; these fixtures treat uncaught exceptions on stderr as failures.
Cancellation and task interfaces
interrupt sets the request flag or causes a documented blocking operation to throw InterruptedException. Such exceptions clear the interrupted status. If a method can throw InterruptedException, propagate it. At a Runnable boundary that cannot throw it, restore the flag and return or let an explicit cancellation policy act. isInterrupted observes without clearing; the static interrupted method tests and clears the current thread’s flag. Runnable.run returns void and cannot declare a checked exception; Callable<V>.call returns a value and may throw checked exceptions. Calling call directly does not schedule work. Executors and Future arrive in Chapter 32.
Interrupt a waiting worker
import java.time.Duration;import java.util.concurrent.*;public class Main { // Only finite tasks and timed coordination are used in these examples. static void finish(Thread thread) throws InterruptedException { try { if (!thread.join(Duration.ofSeconds(3))) { thread.interrupt(); if (!thread.join(Duration.ofSeconds(3))) throw new AssertionError("worker did not stop"); throw new AssertionError("worker timed out"); } } catch (InterruptedException e) { thread.interrupt(); throw e; } } static void await(CountDownLatch latch) { try { if (!latch.await(3, TimeUnit.SECONDS)) throw new AssertionError("latch timed out"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new AssertionError("unexpected cancellation", e); } } public static void main(String[] args) throws Exception { CountDownLatch ready = new CountDownLatch(1); CountDownLatch gate = new CountDownLatch(1); Thread worker = new Thread(() -> { ready.countDown(); try { if (!gate.await(3, TimeUnit.SECONDS)) throw new AssertionError("cancel timed out"); throw new AssertionError("unexpected release"); } catch (InterruptedException e) { System.out.println("cleared: " + !Thread.currentThread().isInterrupted()); Thread.currentThread().interrupt(); System.out.println("restored: " + Thread.currentThread().isInterrupted()); } }); worker.start(); try { await(ready); } finally { worker.interrupt(); finish(worker); } System.out.println("terminated: " + !worker.isAlive()); }}Expected output:
cleared: truerestored: trueterminated: trueThe readiness signal is not proof of a particular thread state. Whether interrupt arrives just before or during await, the interruptible wait reports cancellation. The worker restores its flag and exits.
Preview a result-bearing task
import java.time.Duration;import java.util.concurrent.*;public class Main {
public static void main(String[] args) throws Exception { Callable<Integer> count = () -> 6 * 7; System.out.println(count.call()); Thread.currentThread().interrupt(); System.out.println(Thread.currentThread().isInterrupted()); System.out.println(Thread.interrupted()); System.out.println(Thread.currentThread().isInterrupted()); }}Expected output:
42truetruefalsecall executes synchronously here. The demonstration clears the main thread’s deliberately set interrupt flag; application code should not clear a real cancellation request accidentally.
Common mistakes
Do not call run expecting a new thread, call start twice, infer completion from sleep, or catch InterruptedException and resume as if nothing happened. A timed join must be checked. Interrupt is a request, not a kill operation.
Practice
Run a named worker that adds two numbers and prints its own name and result. Start it once, use the bounded completion helper, then print its final lifecycle state.
Expected output:
sum-worker: 13TERMINATEDCompare your answer with the manual practice criteria.
Official reading: Thread · Callable · CountDownLatch. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Thread lifecycle and interruption — knowledge check
Original concurrency questions. Java 21-compatible scope.
Which call schedules a platform thread?
Which state is safe to observe after successful termination join?
What does interrupt generally request?
What does InterruptedException normally do to the interrupt flag?
Does calling Callable.call directly create a thread?