java线程中含有waiting与blocked两种状态,两种状态有着明显的区别,本文从jdk源码中两种状态的设计角度和状态进入角度来分析两者的区别。
源码分析
/*
* 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,
处于 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,
文档介绍了导致线程进入Wating
状态的原因以及如何退出Wating
状态。
区别
线程可以通过wait
,join
,LockSupport.park
方式进入wating
状态,进入wating状态的线程等待唤醒(notify或notifyAll)才有机会获取cpu的时间片段来继续执行。
线程的 blocked
状态往往是无法进入同步方法/代码块来完成的。这是因为无法获取到与同步方法/代码块相关联的锁。
与wating状态相关联的是等待队列,与blocked状态相关的是同步队列,一个线程由等待队列迁移到同步队列时,线程状态将会由wating
转化为blocked
。可以这样说,blocked
状态是处于wating
状态的线程重新焕发生命力的必由之路。