Thread Lifecycle & Monitor Coordination
Picture a small restaurant counter guarded by one Key. Once you see how threads move between the Hallway (BLOCKED), the Counter (holding the Key), and the Bench (WAITING), wait(), notifyAll(), and Producer-Consumer bugs stop feeling mysterious.
1. The Six States of a Java Thread
Thread.StateNEW (before start()), RUNNABLE (ready/running), BLOCKED (Hallway: waiting for a synchronized Key), WAITING (Bench: wait()/join()), TIMED_WAITING (Timer: sleep(ms)/wait(ms)/join(ms)), TERMINATED (done). Notified threads re-enter BLOCKED before RUNNABLE. Calling start() on any non-NEW thread throws IllegalThreadStateException.
A thread is like a kitchen worker: hired but not clocked in (NEW), working on the floor (RUNNABLE), stuck in the Hallway waiting for the Key (BLOCKED), resting on the Bench waiting for the Bell (WAITING), on a Timer pause (TIMED_WAITING), or clocked out for good (TERMINATED).
The distinction tested most often is BLOCKED vs WAITING. BLOCKED means a thread is waiting in the for a synchronized Key. WAITING means it paused indefinitely via wait() (sitting in the ) or via join().
Interactive 6-State Java Thread Lifecycle
Click any state box to inspect transitions & Key rulesReady or actively running on a CPU core
Entered after start(). Java merges "Ready" (in the OS scheduler queue) and "Running" (on CPU) into one state: RUNNABLE.
getState() strictly for debugging and observation — never for synchronization decisions, because a thread's state can change immediately after getState() returns.Lecture 3's quick-reference diagram uses shorthand showing
WAITING → RUNNABLE on notify(). What the JVM actually does (and what Lecture 2 notes explicitly) is WAITING → BLOCKED (Hallway, competing to re-acquire the Key) → RUNNABLE once it wins the Key again. Mentioning that middle BLOCKED step is strong Level-6 detail.
You call worker.start() a second time while worker is still running (or after it finishes). What does the JVM do?
start() is only valid while a thread is in NEW. Calling it on a RUNNABLE, WAITING, or TERMINATED thread always throws IllegalThreadStateException. Instantiate a new Thread instead.
2. Lab 1: Predict KitchenWorker Step by Step
Week 3 Tutorial Q1
worker.getState() is deterministic before start() (NEW) and after join() (TERMINATED), but timing-dependent right after start() and after Thread.sleep(500). While main executes worker.join(), main is WAITING and worker stays TIMED_WAITING until its 2000 ms sleep ends.
worker and main will be in, then click Check & Step →. Toggle Slow CPU to see why Lines 4 and 6 can vary across runs (Tutorial Q1 Task 2).
Interactive Tracer: LifecycleDemo + KitchenWorker
Live JVM Thread States
Show console trace log
Thread.sleep(2000), but the OS scheduler makes no guarantee. Toggle Slow CPU above to see Line 6 catch worker still in RUNNABLE.main calls worker.join() while worker still has ~1500 ms left in Thread.sleep(2000). main enters WAITING, while worker stays in TIMED_WAITING until its Timer ends.
3. Unified Lab: Inside the Monitor & OrderCounter
Week 3 Tutorial Q2
BLOCKED) → Counter (Key Owner) → Bench (Wait Set · WAITING). wait() drops the Key and resumes on the next line — so if skips rechecking and lets a second Chef call poll() on an empty queue (Preparing: null). With 2 Waiters + 2 Chefs sharing one Bench, notify() wakes an arbitrary sleeper and can cause a lost wake-up hang (all threads WAITING). Always use while + notifyAll().
Every has the same 3 rooms from left to right: the Hallway (BLOCKED — waiting for the Key), the Counter (holding the Key), and the Bench (WAITING — dropped the Key via wait()). Watch the thread chips pinned to the Java code on the right to see which line each thread resumes on.
Unified OrderCounter Monitor Board + Pinned Code Lines
orders, cap=1):
1. Hallway (Entry Set · BLOCKED)
2. Counter (Key Owner)
3. Bench (Wait Set · WAITING)
Show event log
notify() because all waiting threads have the same role (Lecture 2: "use only when all waiters are equivalent"). As soon as 2+ roles share one Bench, notify() risks a lost wake-up hang — switch to notifyAll() (or separate ReentrantLock Conditions in Module 4).Chef-1 acquires the Counter Key, then calls Thread.sleep(2000) inside synchronized takeOrder(). What happens to the Key?
Thread.sleep() never releases any monitor lock. While Chef-1 is in TIMED_WAITING, Waiters attempting to enter placeOrder() sit in the Hallway in state BLOCKED.
4. Java Code, Translated into Plain English
Lecture 2 & 3wait/notifyAll only while holding that object's lock (else IllegalMonitorStateException), (2) always wait in a while loop, (3) prefer notifyAll() on a shared Bench, (4) keep slow work (sleep/I/O) outside synchronized.
Broken vs Fixed OrderCounter.takeOrder()
public synchronized String takeOrder() Acquire this Counter's Key throws InterruptedException { if (orders.isEmpty()) { Bug: checks once; never rechecks after wakeup wait(); Drop Key & sit on Bench; resume on next line } String order = orders.poll(); Returns null if another Chef took last order notify(); Bug: wakes 1 arbitrary sleeper (may be same role) return order; Exit method & release Key }
if does not recheck and orders.poll() returns null (Preparing: null); (2) With 2 Waiters + 2 Chefs, notify() can wake a same-role thread and leave all threads stuck in WAITING.
Keep slow work (sleep / cooking) outside synchronized
public synchronized String takeOrder() throws InterruptedException {
while (orders.isEmpty()) wait();
String order = orders.poll();
Thread.sleep(300); // Holds Counter Key while cooking!
notifyAll();
return order;
}
BLOCKED in the Hallway for 300 ms even though the queue itself only needed microseconds.
5. Clean Shutdowns: SingleSlotMailBox
Week02ThreeTry.zip
SingleSlotMailBox, consume() retries wait(500) 3 times; when attempts >= 3, it calls stop() (setting stopped = true + notifyAll()) before throwing TimeoutException. Because Producer sleeps 5000 ms, the timeout path wins — Main's poison pill produce(-1) never gets consumed.
Week02ThreeTry.zip implements two polite ways to close the mailbox without deprecated Thread.stop(): if the Producer finishes normally, Main drops a (-1); if the Producer is too slow, the Consumer times out after 3 × 500 ms and calls stop() first.
In Producer.java, the Producer sleeps 5000 ms after producing item 1. In SingleSlotMailBox.consume(), the Consumer gives up after 3 × wait(500) (~1.5 s). Does Main's poison pill mailBox.produce(-1) ever reach the Consumer?
wait(500) retries expire (~1.5 s), so Consumer calls stop() (setting stopped = true) and exits on TimeoutException. When Producer later checks if (box.isStopped()) break; and Main calls mailBox.produce(-1), produce() sees if (stopped) return false; — the -1 is never placed or consumed.
Exact Order in SingleSlotMailBox.consume() on Timeout
stop() runs before throw TimeoutException
Thread.stop(), suspend(), or resume() — they can leave shared objects corrupted or Keys permanently held.6. Exam Ledger: Monitor & Thread Methods
Exam Tablewait() vs notify()/notifyAll() vs sleep() vs join()
| Method | Defined On | Must Hold Lock? | Releases Lock? | Thread State & Wakeup |
|---|---|---|---|---|
| obj.wait() | Object |
YES (else IllegalMonitorStateException) |
YES — releases only obj's Key |
WAITING → notify/notifyAll → BLOCKED (re-lock) → RUNNABLE. |
| obj.wait(ms) | Object |
YES (else IllegalMonitorStateException) |
YES — releases only obj's Key |
TIMED_WAITING → Bell or Timer → BLOCKED (re-lock) → RUNNABLE. |
| obj.notify() / notifyAll() | Object |
YES (else IllegalMonitorStateException) |
NO — keeps Key until leaving synchronized |
Caller stays RUNNABLE; woken thread(s) move from Bench → Hallway (BLOCKED). |
| Thread.sleep(ms) | Thread (static) |
No | NO — keeps all held Keys | TIMED_WAITING → Timer ends or interrupt() → RUNNABLE. |
| t.join() | Thread |
No | Does not release unrelated Keys | WAITING (the caller!) until target thread t reaches TERMINATED. |
7. Exam Trace Checks
Self-TestAt ~500 ms in LifecycleDemo, worker is inside Thread.sleep(2000) and main calls worker.join() (no timeout). What are both states right then?
main called join() with no timeout, so main enters WAITING until worker terminates. Meanwhile worker still has ~1500 ms left in Thread.sleep(2000), so worker is in TIMED_WAITING. Neither thread is competing for a monitor Key, so neither is BLOCKED.
Chef-1 enters synchronized takeOrder() and calls Thread.sleep(2000). Waiter-1 calls synchronized placeOrder("Burger") on the same OrderCounter. What state does Waiter-1 enter?
synchronized instance methods share the same this monitor Key. Because Thread.sleep() never releases any lock, Chef-1 keeps the Key while sleeping in TIMED_WAITING, forcing Waiter-1 into the Hallway (Entry Set) in state BLOCKED.
A 1-slot OrderCounter has 2 Waiters and 2 Chefs. Both methods use while loops, but call notify() instead of notifyAll(). Which statement is true?
public synchronized void placeOrder(String o) throws InterruptedException {
while (orders.size() == 1) wait();
orders.add(o);
notify();
}
notify() wakes one arbitrary sleeper. If Chef-1 consumes and wakes Chef-2 (instead of a Waiter), Chef-2 rechecks while (orders.isEmpty()) and goes back to the Bench. All 4 threads end up in WAITING — a lost wake-up hang (often loosely called deadlock, though no lock cycle exists). Fix: use notifyAll().
8. Module 3 Mastery Checklist
Saved locallyTick off each skill once you can explain it aloud from memory (syncs to your Course Map).