Java線程狀態中BLOCKED和WAITING有什麼區別?

剛纔在看CSDN的問答時,發現這個問題。原問題的作者是在觀察jstack的輸出時提出的疑問,那麼BLOCKED和WAITING有什麼區別呢?
答覆在JDK源碼中可以找到,如下是java.lang.Thread.State類的一部分註釋。

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

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

從中可以清晰的得到線程處於BLOCKED和WAITING狀態的場景。

BLOCKED狀態

線程處於BLOCKED狀態的場景。

  • 當前線程在等待一個monitor lock,比如等待執行synchronized代碼塊或者使用synchronized標記的方法。
  • 在synchronized塊中循環調用Object類型的wait方法,如下是樣例
    synchronized(this)
    {
    while (flag)
    {
    obj.wait();
    }
    // some other code
    }

WAITING狀態

線程處於WAITING狀態的場景。

  • 調用Object對象的wait方法,但沒有指定超時值。
  • 調用Thread對象的join方法,但沒有指定超時值。
  • 調用LockSupport對象的park方法。

提到WAITING狀態,順便提一下TIMED_WAITING狀態的場景。

TIMED_WAITING狀態

線程處於TIMED_WAITING狀態的場景。

  • 調用Thread.sleep方法。
  • 調用Object對象的wait方法,指定超時值。
  • 調用Thread對象的join方法,指定超時值。
  • 調用LockSupport對象的parkNanos方法。
  • 調用LockSupport對象的parkUntil方法。
歡迎訪問Jackie的家,http://jackieathome.sinaapp.com/,如需轉載文章,請註明出處。
發佈了70 篇原創文章 · 獲贊 52 · 訪問量 28萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章