1. 程式人生 > >Java線程狀態中BLOCKED和WAITING有什麽差別?

Java線程狀態中BLOCKED和WAITING有什麽差別?

family osi amp block method flag ack san stack

剛才在看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
* [email protected]

/* */ 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:
* [email protected] Object#wait() Object.wait} with no timeout
* [email protected] #join() Thread.join} with no timeout
* [email protected]

/* */ 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/,如需轉載文章,請註明出處。

Java線程狀態中BLOCKED和WAITING有什麽差別?