线程的状态

文章目录

  • 前言
  • 二、各状态详解
    • 就绪状态 & running
    • 阻塞(BLOCKED)
    • WAITING
    • TIMED_WAITING
  • 总结


前言

线程几种状态的解释。


# 一、线程的状态

线程的状态有六种:在Thread类里面的State 枚举中展示

  1. NEW
  2. RUNNABLE
又包含两种
就绪状态
RUNNING
  1. BLOCKED
  2. WAITING
  3. TIMED_WAITING
  4. TERMINATED

二、各状态详解

就绪状态 & running

即jVM已经准备好了,线程在等待抢CPU时间片。抢到就可执行,就处于RUNNING。
例如start 方法,或者是yield方法等之后,线程都是jvm已经准备好了,锁也拿到了,只是等待操作系统的调度

阻塞(BLOCKED)

java api

/**
         * 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

由java api 我们可以看到是在获取monitor 时,处于此状态,而获取monitor 就是在synchronized 调用时。

WAITING

java api

/**
         * Thread state for a waiting thread.
         * A thread is in the waiting state due to calling one of the
         * following methods:
         * 
    *
  • {@link Object#wait() Object.wait} with no timeout
  • *
  • {@link #join() Thread.join} with no timeout
  • *
  • {@link LockSupport#park() LockSupport.park}
  • *
* *

A thread in the waiting state is waiting for another thread to * perform a particular action. * * For example, a thread that has called Object.wait() * on an object is waiting for another thread to call * Object.notify() or Object.notifyAll() on * that object. A thread that has called Thread.join() * is waiting for a specified thread to terminate. */ WAITING,

由上可以看到是在wait() 方法调用后进入WAITING状态,而join其实就是通过wait()来实现的。

TIMED_WAITING

和上面一样,只是多了一个超时时间。


总结

我们可以看到线程的状态分为JVM内部准备,和操作系统调度。WAITING,BLOCKED这些都是内部准备状态,准备好了,线程就绪。之后就是操作系统的调度了,调度到了就运行。

你可能感兴趣的:(多线程,高并发,线程状态)