JAVA - Zero to Hero / Multithreading

Thread Lifecycle

A thread in Java goes through various states from creation to termination. These stages form the Thread Lifecycle.


🚦 Lifecycle States of a Thread:

  1. New

  2. Runnable

  3. Running

  4. Blocked/Waiting

  5. Terminated (Dead)


1️⃣ New

  • The thread is created but not started yet.

  • Happens when you create a thread object using new.

🧾 Example:

Thread t = new Thread(); // NEW state

2️⃣ Runnable

  • The thread is ready to run, but it’s waiting for the CPU.

  • Happens after calling .start().

🧾 Example:

t.start(); // Now in RUNNABLE state

3️⃣ Running

  • The thread is actively executing the run() method.

  • It moves from Runnable → Running when the CPU selects it.

🧠 Note:

  • You cannot control when it moves to running — the CPU scheduler decides.


4️⃣ Blocked / Waiting / Timed Waiting

A thread moves to waiting states when:

  • It’s waiting for another thread or resource.

  • It’s paused for a specific time.

🔸 Blocked:

Waiting to acquire a lock held by another thread.

🔸 Waiting:

Waiting indefinitely until notified.

🔸 Timed Waiting:

Waiting for a fixed time (e.g., using sleep() or join(timeout))

🧾 Example:

Thread.sleep(2000);  // Moves to TIMED_WAITING state

5️⃣ Terminated (Dead)

  • The thread has finished executing or was forcefully stopped.

  • Once dead, it cannot be restarted.

🧾 Example:

public void run() {
    System.out.println("Thread ended.");
}

🧠 Summary Table

State

Description

New

Thread object created

Runnable

.start() called; ready to run

Running

CPU selected the thread

Blocked / Waiting

Temporarily not running

Terminated

Thread has finished or stopped