Java中线程的状态

线程的状态

在操作系统中主要存在五种状态:新建状态,就绪状态,运行状态,等待状态,结束状态

状态转换图

新建状态(new)
  ↓ start()
就绪状态(ready)
  ↓ CPU调度
运行状态(running)
  ├─ 没有拿到锁资源(join(), sleep(), wait()) → 等待状态(waiting)
  ↓ 
结束状态(terminated)

Java线程的6种状态

状态 含义 典型触发方式
NEW 新建状态 new Thread() 创建了线程对象,但尚未调用 start()
RUNNABLE 可运行状态 调用了 start(),线程已启动,正在等待 CPU 时间片(就绪)或正在执行(运行中)
BLOCKED 阻塞状态 线程试图获取一个被其他线程持有的 synchronized 锁,进入阻塞队列等待
WAITING 无限期等待 调用 Object.wait()Thread.join()LockSupport.park(),需其他线程显式唤醒
TIMED_WAITING 限时等待 调用 Thread.sleep(time)Object.wait(timeout)Thread.join(timeout) 等带超时参数的方法
TERMINATED 终止状态 线程的 run() 方法执行完毕,或因未捕获异常而退出

RUNNABLE 在 JVM 层面 不区分“就绪”和“运行中”,两者都归为 RUNNABLE。
这些是 JVM 定义的状态,与操作系统线程状态不完全一一对应。

状态转换图

NEW 
  ↓ start()
RUNNABLE(CPU调度/CPU没有调度)
  ├─ 正常执行 → TERMINATED
  ├─ 遇到 synchronized 锁竞争 → BLOCKED
  ├─ 调用 wait()/join()/park() → WAITING
  └─ 调用 sleep()/wait(timeout) → TIMED_WAITING

BLOCKED →(获得锁)→ RUNNABLE
WAITING →(被 notify()/interrupt() 唤醒)→ RUNNABLE
TIMED_WAITING →(超时 or 被 interrupt())→ RUNNABLE

在Java中验证线程的状态

  1. NEW
public class NewState {
    public static void main(String[] args) {
        Thread t = new Thread(() -> {});
        System.out.println(t.getState()); // NEW
    }
}
  1. RUNNABLE
public class RunState {
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("playing...");
            }
        });
        t.start();
        System.out.println(t.getState()); // RUNNABLE
    }
}
  1. TERMINATED
public class TerminalState {
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                System.out.println("t throw InterruptedException");
            }
        });
        t.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println("main throw InterruptedException");
        }
        System.out.println(t.getState()); // TERMINATED
    }
}
  1. BLOCKED
public class BlockedState {

    public static void main(String[] args) throws InterruptedException {
        Object obj = new Object();
        Thread t = new Thread(() -> {
            synchronized (obj) {
                System.out.println("t is running...");
            }
        });
        synchronized (obj) {
            t.start();
            System.out.println("main is running...");
            Thread.sleep(500); // 睡眠500ms的作用是什么?
            System.out.println(t.getState()); // BLOCKED
        }
    }
}

为什么需要 sleep(500)?

  • 如果没有 Thread.sleep(500),主线程可能会很快执行完 synchronized 块(释放锁),然后立即打印 t.getState()。
    • 此时线程 t 可能:还没来得及启动(虽然调用了 start(),但线程调度需要时间),或者刚启动但还没尝试获取锁。
      那么 t.getState() 可能返回的是 NEW 或 RUNNABLE,而不是我们期望观察到的 阻塞状态(BLOCKED)。
  • 加入 sleep(500) 后:
    • 主线程在持有锁的情况下睡 500 毫秒,给线程 t 充足的时间去启动并尝试获取 obj 的锁
      由于锁被主线程占用,t 会被阻塞,进入 BLOCKED 状态。所以 System.out.println(t.getState()); 很可能输出:BLOCKED。
  1. WAITING
public class WaitState {
    public static void main(String[] args) {
        Object obj = new Object();
        Thread t = new Thread(() -> {
            synchronized (obj) {
                try {
                    obj.wait();
                    System.out.println("t is playing...");
                } catch (InterruptedException e) {
                    System.out.println("t wait catch InterruptedException");
                }
            }
        });

        t.start();

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            System.out.println("main sleep catch InterruptedException");
        }
        System.out.println(t.getState()); // WAITING

        synchronized (obj) {
            obj.notify(); // 唤醒 t
        }
        try {
            t.join(); // 等待 t 结束
        } catch (InterruptedException e) {
            System.out.println("t join catch InterruptedException");
        }
    }
}
  1. TIMED_WAITING
public class TimedWaitState {
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("t wait catch InterruptedException");
            }
        });

        t.start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            System.out.println("t wait catch InterruptedException");
        }

        System.out.println(t.getState()); // TIMED_WAITING
    }
}

附录

// 源码:Java中Thread类在其生命周期中定义的 6 种状态
public enum State {
  /**
   * Thread state for a thread which has not yet started.
   */
  NEW,

  /**
   * Thread state for a runnable thread.  A thread in the runnable
   * state is executing in the Java virtual machine but it may
   * be waiting for other resources from the operating system
   * such as processor.
   */
  RUNNABLE,

  /**
   * Thread state for a thread blocked waiting for a monitor lock.
   * A thread in the blocked state is waiting for a monitor lock
   * to enter a synchronized block/method or
   * reenter a synchronized block/method after calling
   * {@link Object#wait() Object.wait}.
   */
  BLOCKED,

  /**
   * Thread state for a waiting thread.
   * A thread is in the waiting state due to calling one of the
   * following methods:
   * <ul>
   *   <li>{@link Object#wait() Object.wait} with no timeout</li>
   *   <li>{@link #join() Thread.join} with no timeout</li>
   *   <li>{@link LockSupport#park() LockSupport.park}</li>
   * </ul>
   *
   * <p>A thread in the waiting state is waiting for another thread to
   * perform a particular action.
   *
   * For example, a thread that has called <tt>Object.wait()</tt>
   * on an object is waiting for another thread to call
   * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
   * that object. A thread that has called <tt>Thread.join()</tt>
   * is waiting for a specified thread to terminate.
   */
  WAITING,

  /**
   * Thread state for a waiting thread with a specified waiting time.
   * A thread is in the timed waiting state due to calling one of
   * the following methods with a specified positive waiting time:
   * <ul>
   *   <li>{@link #sleep Thread.sleep}</li>
   *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
   *   <li>{@link #join(long) Thread.join} with timeout</li>
   *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
   *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
   * </ul>
   */
  TIMED_WAITING,

  /**
   * Thread state for a terminated thread.
   * The thread has completed execution.
   */
  TERMINATED;
}

posted on 2026-04-12 09:42  _pepsicola  阅读(2)  评论(0)    收藏  举报

导航