Java线程状态转换,WAITING到BLOCKED还是RUNNABLE? [英] Java thread state transition, WAITING to BLOCKED, or RUNNABLE?

查看:868
本文介绍了Java线程状态转换,WAITING到BLOCKED还是RUNNABLE?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SO共识与互联网上几乎所有Java线程状态图之间似乎存在差异;具体来说,关于 notify()或<$ c $之后来自 WAITING 的线程状态转换 c> notifyAll()被调用...




  • 等待 state。


    线程状态被阻塞等待监视器锁定。处于阻塞状态的线程
    正在等待监视器锁定输入
    同步块/方法,或者在
    调用 Object.wait <之后重新输入同步块/方法/ code>。


    这在 对象#通知()


    在当前的
    线程放弃对该对象的锁定之前,唤醒的线程将无法继续。


    对象#wait()


    线程然后等待直到它可以重新获得监视器
    的所有权并继续执行。



    There seems to be a discrepancy between SO consensus and nearly every Java thread state diagram on the Internet; specifically, regarding thread state transition from WAITING after notify() or notifyAll() is invoked...

    • WAITING never goes directly to RUNNABLE
    • The thread is WAITING until it is notified...Then it becomes BLOCKED...
    • Once this thread is notified, it will not be runnable...This is..Blocked State.

    So the concensus on SO is: a thread transitions from WAITING to BLOCKED after invoking notify() or notifyAll(); diagram below illustrates this transition in green.

    Question

    Why do most state diagrams on the web illustrate the transition from WAITING to RUNNABLE, not BLOCKED? Depiction in red shows the incorrect transition; am I missing something?

    解决方案

    Any diagram that shows a notify invocation bringing a thread from WAITING to RUNNABLE is wrong (or is using an unclarified shortcut). Once a thread gets awoken from a notify (or even from a spurious wakeup) it needs to relock the monitor of the object on which it was waiting. This is the BLOCKED 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 Object.wait.

    This is explained in the javadoc of Object#notify():

    The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object.

    and Object#wait()

    The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

    这篇关于Java线程状态转换,WAITING到BLOCKED还是RUNNABLE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆