Java 中 Thread 的状态

Java juc 面试 About 1,690 words

示意图

thread status.png

NEW 初始化状态

new一个Thread(Runnable)Thread子类等(不调用start()方法),线程就进入NEW状态。

Thread thread1 = new Thread(() -> {

});
// thread1 state#NEW
System.out.println("thread1 state#" + thread1.getState().name());

RUNNABLE 可运行状态

可运行状态又分为就绪状态和运行中状态。

Thread thread2 = new Thread(() -> { });
thread2.start();
// thread2 state#RUNNABLE
System.out.println("thread2 state#" + thread2.getState().name());

READY 就绪状态

  1. 调用start()方法
  2. 调用yield()方法
  3. sleep()方法结束后
  4. 其他线程join()
  5. 当前线程时间片用完了

RUNNING 运行中状态

正在运行任务的线程。

TERMINATED 终止状态

任务执行完成后状态为TERMINATED

Thread thread3 = new Thread(() -> { });
thread3.start();
TimeUnit.MILLISECONDS.sleep(10);
// thread3 state#TERMINATED
System.out.println("thread3 state#" + thread3.getState().name());

TIMED_WAITING 等待超时状态

以下5个方法使RUNNABLE状态的线程变为TIMED_WAITING状态。

  1. Thread.sleep(long)
  2. Object.wait(long)
  3. Thread.join(long)
  4. LockSupport.parkNanos()
  5. LockSupport.parkUntil()
Thread thread4 = new Thread(() -> {
    LockSupport.parkNanos(1000*1000*1000);
});
thread4.start();
TimeUnit.MILLISECONDS.sleep(10);
// thread4 state#TIMED_WAITING
System.out.println("thread4 state#" + thread4.getState().name());

WAITING 等待状态

以下5个方法使RUNNABLE状态的线程变为TIMED_WAITING状态。

  1. Object.wait()
  2. Thread.join()
  3. LockSupport.park()
Thread thread5 = new Thread(LockSupport::park);
thread5.start();
TimeUnit.MILLISECONDS.sleep(10);
// thread5 state#WAITING
System.out.println("thread5 state#" + thread5.getState().name());

BLOCKED 阻塞状态

等待锁释放

Thread thread6 = new Thread(() -> {
    synchronized (Object.class) {

    }
});
thread6.start();
synchronized (Object.class) {
    TimeUnit.MILLISECONDS.sleep(10);
    // thread6 state#BLOCKED
    System.out.println("thread6 state#" + thread6.getState().name());
}
Views: 3,143 · Posted: 2021-04-11

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh