Concurrency

Threads & Their Lifecycle

A Thread executes a Runnable concurrently with the rest of the program. Threads are the unit of scheduling; understanding their states — and interruption, the cooperative stop mechanism — underlies everything else in concurrency.
  • Start with Thread.ofPlatform().start(task) / new Thread(task).start() — never call run() directly
  • States: NEW → RUNNABLE ⇄ (BLOCKED | WAITING | TIMED_WAITING) → TERMINATED
  • Interruption is cooperative: interrupt() sets a flag; the target must check or be blocked
  • InterruptedException clears the flag — restore it or rethrow, never swallow
  • Daemon threads don't keep the JVM alive
  • In application code, prefer executors over raw threads (EJ 80)
Creating and joining
Thread worker = Thread.ofPlatform().name("loader").start(() -> load(data));
// … do other work …
worker.join();                      // wait for completion

Thread vt = Thread.ofVirtual().start(() -> fetch(url));   // virtual: cheap, see Virtual Threads

Calling run() executes the task on your thread — the classic beginner bug; start() is what creates the new one. A thread terminates when its run method returns or throws; an uncaught exception kills only that thread (install an UncaughtExceptionHandler to at least log it — silent thread death is a notorious production mystery).

Thread states (Thread.getState())
StateMeaningTypical cause
NEWcreated, not startedbefore start()
RUNNABLErunning or ready to runnormal execution
BLOCKEDwaiting for a monitor lockcontended synchronized
WAITINGparked indefinitelyjoin(), wait(), park()
TIMED_WAITINGparked with a deadlinesleep(ms), join(ms), wait(ms)
TERMINATEDrun() finishedcompletion or uncaught exception

Interruption — the only sane way to stop

Responding to interruption
public void run() {
    try {
        while (!Thread.currentThread().isInterrupted()) {
            process(queue.take());          // blocking calls throw InterruptedException
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt(); // restore the flag for callers up-stack
    }
}
Sources
  • Core Java, Volume I: Fundamentals (13th ed.)Ch. 10.1–10.3 — Running Threads; Thread States; Properties
  • Java Concurrency in PracticeCh. 7 — Cancellation and Shutdown
  • Learning Java (6th ed.)Ch. 9 — Threads