线程的状态


前言

线程几种状态的解释。


# 一、线程的状态

线程的状态有六种:在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:
         * <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,

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

TIMED_WAITING

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


总结

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值