java线程waiting与blocked的区别

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:
     * 
    *
  • {@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,

文档介绍了导致线程进入Wating状态的原因以及如何退出Wating状态。

区别

线程可以通过wait,join,LockSupport.park方式进入wating状态,进入wating状态的线程等待唤醒(notify或notifyAll)才有机会获取cpu的时间片段来继续执行

线程的 blocked状态往往是无法进入同步方法/代码块来完成的。这是因为无法获取到与同步方法/代码块相关联的锁。

与wating状态相关联的是等待队列,与blocked状态相关的是同步队列,一个线程由等待队列迁移到同步队列时,线程状态将会由wating转化为blocked可以这样说,blocked状态是处于wating状态的线程重新焕发生命力的必由之路。

你可能感兴趣的:(java线程waiting与blocked的区别)