Java Thread States
Every thread goes through a lifecycle: it is created, runs, may pause to wait for something, and finally ends. Java thread states describe exactly where a thread is in that lifecycle at any moment. Java defines six of them in the Thread.State enum, and getState() tells you which one a thread is in.
Knowing the states helps you understand what your threads are doing, why a program seems stuck, and what a thread dump is telling you. This lesson explains each state with a runnable example that puts a thread into it.
The Six Java Thread States
Thread.State is an enum nested in the Thread class. It has exactly six values.
public class AllStatesDemo {
public static void main(String[] args) {
// Thread.State is an enum with exactly six values
for (Thread.State state : Thread.State.values()) {
System.out.println(state.ordinal() + ": " + state);
}
}
}
Output:
0: NEW
1: RUNNABLE
2: BLOCKED
3: WAITING
4: TIMED_WAITING
5: TERMINATED
| State | Meaning | Typical cause |
|---|---|---|
NEW | Created but not started yet | new Thread(...) before start() |
RUNNABLE | Running, or ready to run as soon as it gets a CPU | After start(), while executing code |
BLOCKED | Waiting to enter a synchronized block or method that another thread holds | Lock contention |
WAITING | Waiting with no time limit for another thread to do something | wait(), join(), LockSupport.park() |
TIMED_WAITING | Waiting with a time limit | sleep(ms), wait(ms), join(ms) |
TERMINATED | Finished; run() has returned or thrown | End of the task |
How the states connect:
start()
NEW ───────────────────► RUNNABLE ─────── run() ends ───────► TERMINATED
│ ▲ ▲
synchronized is busy │ │ │ lock becomes free
▼ │ │
BLOCKED ◄┘
▲
│ after notify(): must get the lock back
│
wait() / join() │ sleep(ms) / wait(ms) / join(ms)
RUNNABLE ────────────► WAITING RUNNABLE ────────────► TIMED_WAITING
◄──────────── ◄────────────
notify() / thread ends time is up / notify / interrupt
Note: These are JVM states, not operating-system states. A thread that is
RUNNABLEmay actually be waiting for a CPU core, or even blocked inside the operating system while reading from a network socket or a file. Java still reports such threads asRUNNABLE.
NEW, RUNNABLE and TERMINATED: The Basic Thread Lifecycle
Every thread passes through these three states. A thread is NEW until you call start(), RUNNABLE while it executes its task, and TERMINATED once run() has finished.
public class NewRunnableTerminatedDemo {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
// Busy calculation: the thread keeps the CPU busy, so it is RUNNABLE
long sum = 0;
for (long i = 0; i < 3_000_000_000L; i++) {
sum += i % 7;
}
System.out.println("worker: sum = " + sum);
}, "worker");
System.out.println("1. after new Thread(): " + worker.getState());
worker.start();
Thread.sleep(50);
System.out.println("2. while calculating : " + worker.getState());
worker.join();
System.out.println("3. after run() ends : " + worker.getState());
}
}
Output (the calculation takes a few seconds):
1. after new Thread(): NEW
2. while calculating : RUNNABLE
worker: sum = 8999999994
3. after run() ends : TERMINATED
How it works:
- Right after
new Thread(...), the thread object exists, but no real thread has been created yet:NEW. - After
start(), the worker loops through three billion numbers. It is busy with the CPU the whole time:RUNNABLE. - After
join()returns,run()has finished:TERMINATED. A terminated thread cannot be restarted; callingstart()again throwsIllegalThreadStateException, as shown in Create a Thread in Java.
TIMED_WAITING: Sleeping and Waiting with a Timeout
A thread is in TIMED_WAITING when it pauses for a limited time. It returns to RUNNABLE when the time is up, or earlier if it is notified or interrupted.
public class TimedWaitingDemo {
public static void main(String[] args) throws InterruptedException {
Thread napper = new Thread(() -> {
try {
Thread.sleep(500); // waits with a time limit
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, "napper");
Thread patient = new Thread(() -> {
try {
napper.join(1000); // join with a timeout is also a timed wait
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, "patient");
napper.start();
patient.start();
Thread.sleep(100);
System.out.println("napper (sleep 500) : " + napper.getState());
System.out.println("patient (join 1000) : " + patient.getState());
patient.join();
System.out.println("after both finished : " + napper.getState() + ", " + patient.getState());
}
}
Output:
napper (sleep 500) : TIMED_WAITING
patient (join 1000) : TIMED_WAITING
after both finished : TERMINATED, TERMINATED
How it works:
nappercallsThread.sleep(500), the most common way to enterTIMED_WAITING.patientcallsnapper.join(1000): wait fornapperto end, but at most one second. Because there is a limit, this is alsoTIMED_WAITING.napperfinishes after 500 ms, which endspatient's wait early, and both threads terminate.
Methods that put a thread into TIMED_WAITING:
| Method | Ends when |
|---|---|
Thread.sleep(millis) | The time is up, or the thread is interrupted |
obj.wait(millis) | Notified, time is up, or interrupted |
t.join(millis) | Thread t ends, time is up, or interrupted |
LockSupport.parkNanos(nanos) | Unparked, time is up, or interrupted |
WAITING: Waiting Without a Time Limit
A thread is WAITING when it waits for another thread with no time limit. It stays there until another thread acts: calls notify()/notifyAll() on the same object, or the joined thread finishes.
public class WaitingDemo {
private static final Object mailbox = new Object();
private static String message; // guarded by mailbox
public static void main(String[] args) throws InterruptedException {
Thread reader = new Thread(() -> {
synchronized (mailbox) {
while (message == null) {
try {
mailbox.wait(); // waits with NO time limit until notified
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
System.out.println("reader got: " + message);
}
}, "reader");
Thread joiner = new Thread(() -> {
try {
reader.join(); // join() without a timeout: WAITING
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, "joiner");
reader.start();
joiner.start();
Thread.sleep(100);
System.out.println("reader (wait()) : " + reader.getState());
System.out.println("joiner (join()) : " + joiner.getState());
synchronized (mailbox) {
message = "Your order has shipped";
mailbox.notify(); // wake the waiting reader
}
joiner.join();
System.out.println("finally : " + reader.getState() + ", " + joiner.getState());
}
}
Output:
reader (wait()) : WAITING
joiner (join()) : WAITING
reader got: Your order has shipped
finally : TERMINATED, TERMINATED
How it works:
readerenters thesynchronized (mailbox)block and finds no message, so it callsmailbox.wait(). That releases the lock and parks the thread inWAITING.joinercallsreader.join()with no timeout, so it isWAITINGtoo, for as long asreaderlives.- Main stores a message and calls
mailbox.notify(). The reader wakes up, sees the message and finishes, which in turn ends the joiner's wait. - The reader checks
message == nullin a loop, because a waiting thread can occasionally wake up without being notified (a "spurious wakeup").
Note:
wait()andnotify()must be called while holding the lock of the same object, insidesynchronized. Otherwise they throwIllegalMonitorStateException. Modern code often uses higher-level tools such asBlockingQueueinstead, which later lessons cover.
BLOCKED: Waiting for a Lock
A thread is BLOCKED when it wants to enter a synchronized block or method, but another thread currently holds that lock. It moves back to RUNNABLE as soon as the lock is released and it manages to take it.
public class BlockedDemo {
private static final Object printerLock = new Object();
static void printDocument(String document) {
synchronized (printerLock) { // only one thread at a time may hold this lock
System.out.println(Thread.currentThread().getName() + " printing " + document);
try {
Thread.sleep(400);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread first = new Thread(() -> printDocument("invoice.pdf"), "first");
Thread second = new Thread(() -> printDocument("receipt.pdf"), "second");
first.start();
Thread.sleep(100); // make sure "first" gets the lock
second.start();
Thread.sleep(100);
System.out.println("first : " + first.getState() + " (holds the lock, sleeping)");
System.out.println("second : " + second.getState() + " (waiting to enter synchronized)");
first.join();
second.join();
System.out.println("done : " + first.getState() + ", " + second.getState());
}
}
Output:
first printing invoice.pdf
first : TIMED_WAITING (holds the lock, sleeping)
second : BLOCKED (waiting to enter synchronized)
second printing receipt.pdf
done : TERMINATED, TERMINATED
How it works:
firstenterssynchronized (printerLock)and then sleeps for 400 ms while still holding the lock. Its own state isTIMED_WAITINGbecause of the sleep.secondreaches the samesynchronizedblock and has to wait for the lock:BLOCKED.- When
firstleaves the block, the lock is released,secondtakes it, prints, and both threads finish.
BLOCKED vs WAITING vs TIMED_WAITING
The three waiting states are easy to mix up. The key question is what the thread is waiting for.
BLOCKED | WAITING | TIMED_WAITING | |
|---|---|---|---|
| Waiting for | A synchronized lock held by another thread | Another thread's action (notify, finishing) | Another thread's action, or the clock |
| Time limit | None | None | Yes |
| Entered by | Reaching a busy synchronized block | wait(), join(), park() | sleep(ms), wait(ms), join(ms), parkNanos |
| Left when | The lock becomes free and the thread gets it | Notified, unparked, or the joined thread ends | Same, or the time runs out |
Reacts to interrupt() | No, it keeps waiting for the lock | Yes, InterruptedException | Yes, InterruptedException |
| Uses CPU | No | No | No |
Note: Many threads stuck in
BLOCKEDon the same lock is a sign of lock contention. Two threads that are eachBLOCKEDwaiting for a lock the other one holds are in a deadlock and will never continue. The Deadlocks lesson later in this section shows how to recognise and avoid that.
Tracking a Thread's Lifecycle Step by Step
The previous examples took single snapshots. This program records every state change of one worker as it computes, sleeps, waits for a lock, waits for a notification, and computes again.
import java.util.ArrayList;
import java.util.List;
public class LifecycleTracker {
private static final Object lock = new Object();
private static boolean ready = false;
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
busy(150); // RUNNABLE
pause(200); // TIMED_WAITING
synchronized (lock) { // BLOCKED until main releases the lock
while (!ready) {
try {
lock.wait(); // WAITING until notified
} catch (InterruptedException e) {
return;
}
}
}
busy(150); // RUNNABLE again
}, "worker");
List<Thread.State> history = new ArrayList<>();
Thread watcher = new Thread(() -> {
Thread.State last = null;
while (true) {
Thread.State now = worker.getState();
if (now != last) {
history.add(now); // record every change of state
last = now;
}
if (now == Thread.State.TERMINATED) {
return;
}
Thread.onSpinWait();
}
}, "watcher");
watcher.start();
Thread.sleep(50);
worker.start();
Thread.sleep(250); // worker is busy, then sleeping
synchronized (lock) {
Thread.sleep(300); // hold the lock: worker becomes BLOCKED
}
Thread.sleep(200); // worker got the lock and is now WAITING
synchronized (lock) {
ready = true;
lock.notify();
}
watcher.join();
System.out.println(String.join(" -> ", history.stream().map(Enum::name).toList()));
}
static void busy(long millis) {
long end = System.nanoTime() + millis * 1_000_000;
while (System.nanoTime() < end) {
Thread.onSpinWait();
}
}
static void pause(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
Output (on a very busy machine, the watcher can occasionally miss one of the very short RUNNABLE or BLOCKED steps):
NEW -> RUNNABLE -> TIMED_WAITING -> RUNNABLE -> BLOCKED -> RUNNABLE -> WAITING -> BLOCKED -> RUNNABLE -> TERMINATED
How it works:
- The
watcherthread checksworker.getState()in a tight loop and stores the state each time it changes.Thread.onSpinWait()tells the CPU this is a busy-wait loop. busy(150)keeps the CPU working, so the worker isRUNNABLE.pause(200)sleeps:TIMED_WAITING.- Main takes the lock and holds it for 300 ms. The worker arrives at
synchronized (lock)and isBLOCKEDuntil main lets go. - Once inside, the worker is briefly
RUNNABLE, then callslock.wait():WAITING. - Main calls
notify()while holding the lock. The worker wakes up but must get the lock back beforewait()can return, so it isBLOCKEDfor a moment. This secondBLOCKEDsurprises many developers, and the tracker makes it visible. - Finally the worker computes again (
RUNNABLE) and ends (TERMINATED).
Real-World Example: A Thread Watchdog for a Shop Backend
When a server becomes slow, developers look at the states of its threads, much like a jstack thread dump does. This watchdog takes a snapshot of the shop's worker threads, counts the states, and raises an alert when several threads are BLOCKED on the same lock, a typical sign of a bottleneck.
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
public class Watchdog {
private static final Object inventoryLock = new Object();
private static final Object orderQueue = new Object();
static void sleepQuietly(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws InterruptedException {
// Holds the inventory lock for a long time (a slow database update)
Thread stockUpdater = new Thread(() -> {
synchronized (inventoryLock) {
sleepQuietly(1500);
}
}, "stock-updater");
// Needs the same lock, so it is stuck behind stock-updater
Thread checkout1 = new Thread(() -> { synchronized (inventoryLock) { } }, "checkout-1");
Thread checkout2 = new Thread(() -> { synchronized (inventoryLock) { } }, "checkout-2");
// Idle worker waiting for orders that never arrive
Thread orderWorker = new Thread(() -> {
synchronized (orderQueue) {
try {
orderQueue.wait();
} catch (InterruptedException e) {
System.out.println("order-worker: interrupted, shutting down");
}
}
}, "order-worker");
// Busy calculating
Thread reportBuilder = new Thread(() -> {
long end = System.nanoTime() + 1_000_000_000L;
while (System.nanoTime() < end) {
Thread.onSpinWait();
}
}, "report-builder");
List<Thread> threads = List.of(stockUpdater, checkout1, checkout2, orderWorker, reportBuilder);
stockUpdater.start();
Thread.sleep(50);
for (Thread t : threads.subList(1, threads.size())) {
t.start();
}
Thread.sleep(200);
// Take a snapshot of every thread's state
Map<Thread.State, Integer> counts = new EnumMap<>(Thread.State.class);
System.out.printf("%-15s %s%n", "THREAD", "STATE");
for (Thread t : threads) {
Thread.State state = t.getState();
counts.merge(state, 1, Integer::sum);
String warning = state == Thread.State.BLOCKED ? " <- waiting for a lock" : "";
System.out.printf("%-15s %s%s%n", t.getName(), state, warning);
}
System.out.println("Summary: " + counts);
if (counts.getOrDefault(Thread.State.BLOCKED, 0) >= 2) {
System.out.println("ALERT: several threads are BLOCKED on the same lock");
}
orderWorker.interrupt(); // release the idle worker so the program can end
for (Thread t : threads) {
t.join();
}
System.out.println("All threads TERMINATED: "
+ threads.stream().allMatch(t -> t.getState() == Thread.State.TERMINATED));
}
}
Output:
THREAD STATE
stock-updater TIMED_WAITING
checkout-1 BLOCKED <- waiting for a lock
checkout-2 BLOCKED <- waiting for a lock
order-worker WAITING
report-builder RUNNABLE
Summary: {RUNNABLE=1, BLOCKED=2, WAITING=1, TIMED_WAITING=1}
ALERT: several threads are BLOCKED on the same lock
order-worker: interrupted, shutting down
All threads TERMINATED: true
How it works:
- Five threads, four states.
stock-updatersleeps while holdinginventoryLock(TIMED_WAITING), both checkouts need that lock (BLOCKED),order-workerwaits for orders withwait()(WAITING), andreport-builderkeeps calculating (RUNNABLE). - Snapshot. After 200 ms, the watchdog reads
getState()of each thread once and prints a table. States change all the time, so a snapshot is always a picture of one moment. - Counting with an
EnumMap.counts.merge(state, 1, Integer::sum)adds one per thread. AnEnumMapkeeps its keys in the enum's order, which is why the summary listsRUNNABLEbeforeBLOCKED. - Alert rule. Two or more
BLOCKEDthreads trigger an alert. In a real system, the watchdog would run periodically and also log which thread holds the lock, herestock-updater. - Clean shutdown. The idle
order-workerwould wait forever, so the watchdog interrupts it;wait()throwsInterruptedExceptionand the thread ends. The checkouts get the lock afterstock-updaterfinishes, and finally every thread isTERMINATED.
To see how these threads were created and named, revisit Java Thread Class and Java Runnable Interface. The basics of why threads share locks and data are in Java Threads: Thread Basics.