Java Thread States

Su Suriya Ravichandran Updated 18 Nov 2026
13 min read ·Lesson 185 of 306

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
StateMeaningTypical cause
NEWCreated but not started yetnew Thread(...) before start()
RUNNABLERunning, or ready to run as soon as it gets a CPUAfter start(), while executing code
BLOCKEDWaiting to enter a synchronized block or method that another thread holdsLock contention
WAITINGWaiting with no time limit for another thread to do somethingwait(), join(), LockSupport.park()
TIMED_WAITINGWaiting with a time limitsleep(ms), wait(ms), join(ms)
TERMINATEDFinished; run() has returned or thrownEnd 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 RUNNABLE may 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 as RUNNABLE.


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; calling start() again throws IllegalThreadStateException, 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:

  • napper calls Thread.sleep(500), the most common way to enter TIMED_WAITING.
  • patient calls napper.join(1000): wait for napper to end, but at most one second. Because there is a limit, this is also TIMED_WAITING.
  • napper finishes after 500 ms, which ends patient's wait early, and both threads terminate.

Methods that put a thread into TIMED_WAITING:

MethodEnds 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:

  • reader enters the synchronized (mailbox) block and finds no message, so it calls mailbox.wait(). That releases the lock and parks the thread in WAITING.
  • joiner calls reader.join() with no timeout, so it is WAITING too, for as long as reader lives.
  • 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 == null in a loop, because a waiting thread can occasionally wake up without being notified (a "spurious wakeup").

Note: wait() and notify() must be called while holding the lock of the same object, inside synchronized. Otherwise they throw IllegalMonitorStateException. Modern code often uses higher-level tools such as BlockingQueue instead, 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:

  • first enters synchronized (printerLock) and then sleeps for 400 ms while still holding the lock. Its own state is TIMED_WAITING because of the sleep.
  • second reaches the same synchronized block and has to wait for the lock: BLOCKED.
  • When first leaves the block, the lock is released, second takes 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.

BLOCKEDWAITINGTIMED_WAITING
Waiting forA synchronized lock held by another threadAnother thread's action (notify, finishing)Another thread's action, or the clock
Time limitNoneNoneYes
Entered byReaching a busy synchronized blockwait(), join(), park()sleep(ms), wait(ms), join(ms), parkNanos
Left whenThe lock becomes free and the thread gets itNotified, unparked, or the joined thread endsSame, or the time runs out
Reacts to interrupt()No, it keeps waiting for the lockYes, InterruptedExceptionYes, InterruptedException
Uses CPUNoNoNo

Note: Many threads stuck in BLOCKED on the same lock is a sign of lock contention. Two threads that are each BLOCKED waiting 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 watcher thread checks worker.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 is RUNNABLE. pause(200) sleeps: TIMED_WAITING.
  • Main takes the lock and holds it for 300 ms. The worker arrives at synchronized (lock) and is BLOCKED until main lets go.
  • Once inside, the worker is briefly RUNNABLE, then calls lock.wait(): WAITING.
  • Main calls notify() while holding the lock. The worker wakes up but must get the lock back before wait() can return, so it is BLOCKED for a moment. This second BLOCKED surprises 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:

  1. Five threads, four states. stock-updater sleeps while holding inventoryLock (TIMED_WAITING), both checkouts need that lock (BLOCKED), order-worker waits for orders with wait() (WAITING), and report-builder keeps calculating (RUNNABLE).
  2. 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.
  3. Counting with an EnumMap. counts.merge(state, 1, Integer::sum) adds one per thread. An EnumMap keeps its keys in the enum's order, which is why the summary lists RUNNABLE before BLOCKED.
  4. Alert rule. Two or more BLOCKED threads trigger an alert. In a real system, the watchdog would run periodically and also log which thread holds the lock, here stock-updater.
  5. Clean shutdown. The idle order-worker would wait forever, so the watchdog interrupts it; wait() throws InterruptedException and the thread ends. The checkouts get the lock after stock-updater finishes, and finally every thread is TERMINATED.

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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Thread States and get answers drawn from it.

Signed-in readers only.