前言
线程几种状态的解释。
# 一、线程的状态
线程的状态有六种:在Thread类里面的State 枚举中展示
- NEW
- RUNNABLE
-
又包含两种
- 就绪状态
- RUNNING
- BLOCKED
- WAITING
- TIMED_WAITING
- 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这些都是内部准备状态,准备好了,线程就绪。之后就是操作系统的调度了,调度到了就运行。