Java.Multithreding.What states can a thread be in?

Let’s walk through the 6 thread states in Java, according to the java.lang.Thread.State enum.


🧵 Java Thread States

StateWhen It Happens
NEWThread object is created, but start() has not been called
RUNNABLEThread is ready to run or currently running
BLOCKEDWaiting to acquire a monitor lock (e.g. synchronized)
WAITINGWaiting indefinitely for another thread to signal
TIMED_WAITINGWaiting for a specified time (e.g. sleep(), join(timeout))
TERMINATEDThread has completed execution or thrown an exception

🔍 Detailed Breakdown

1. NEW

Thread t = new Thread(); // Not started yet

Thread object is created, but not started.

Can only move to RUNNABLE by calling start().

2. RUNNABLE

t.start();

Thread has been started and is ready to run or running

Managed by OS thread scheduler

Includes actively executing and waiting for CPU

3. BLOCKED

synchronized(obj) {
    // Thread B blocks if Thread A is holding the lock
}

Thread is waiting to acquire a monitor lock

Different from WAITING, which is voluntary

4. WAITING

obj.wait();
t.join();             // Without timeout
future.get();         // When result isn’t ready yet

Thread is waiting indefinitely

Only proceeds when another thread signals (notify(), join() completes, etc.)

5. TIMED_WAITING

Thread.sleep(1000);
t.join(5000);
obj.wait(1000);

Waiting for a specific amount of time

Will return after timeout or signal, whichever comes first

6. TERMINATED

public void run() {
    System.out.println("done"); // finishes
}

Thread has finished execution or died due to an uncaught exception

Cannot be restarted

🧠 Bonus: Transition Diagram (Text Format)

NEW --> RUNNABLE --> [BLOCKED / WAITING / TIMED_WAITING] --> RUNNABLE --> TERMINATED

BLOCKED → waiting for lock

WAITING → waiting for another thread

TIMED_WAITING → waiting for timeout or event

🧪 Example: Viewing a Thread’s State

Thread t = new Thread(() -> {
    try {
        Thread.sleep(2000);
    } catch (InterruptedException ignored) {}
});

System.out.println(t.getState()); // NEW
t.start();
System.out.println(t.getState()); // RUNNABLE or TIMED_WAITING (briefly)

🧠 Summary Table

StateDescriptionCommon Causes
NEWCreated but not startednew Thread()
RUNNABLEReady or runningstart() called
BLOCKEDWaiting for synchronized locksynchronized(obj) contention
WAITINGWaiting indefinitelywait(), join(), LockSupport.park()
TIMED_WAITINGWaiting for timeoutsleep(), join(timeout)
TERMINATEDExecution finished or failedrun() completed or exception thrown
This entry was posted in Без рубрики. Bookmark the permalink.