V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
andybest
V2EX  ›  问与答

为什么java执行中线程状态标记为RUNNABLE而不是RUNNING?

  •  
  •   andybest · 2013-06-18 12:33:43 +08:00 · 3195 次点击
    这是一个创建于 3964 天前的主题,其中的信息可能已经有所发展或是发生改变。
    A thread state. A thread can be in one of the following states:

    NEW
    A thread that has not yet started is in this state.
    RUNNABLE
    A thread executing in the Java virtual machine is in this state.
    BLOCKED
    A thread that is blocked waiting for a monitor lock is in this state.
    WAITING
    A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
    TIMED_WAITING
    A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
    TERMINATED
    A thread that has exited is in this state.

    参考:http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.State.html


    对于RUNNABLE状态有点违反我的常识,既然是“A thread executing”,为什么不标记为RUNNING或者EXECUTEING?
    那又为什么WAITING状态不是WAITABLE?


    各位认为是出于什么考虑这样做的?
    7 条回复    1970-01-01 08:00:00 +08:00
    TempAccount
        1
    TempAccount  
       2013-06-18 12:45:58 +08:00   ❤️ 1
    我的理解线程runnable是vm的事, 但是它running不running还得OS说了算
    andybest
        2
    andybest  
    OP
       2013-06-18 12:49:00 +08:00
    @TempAccount 谢谢,很有道理!

    但是WAITING又怎么理解呢?既然VM无法决定是否running,同样也应无法决定是否waiting吧?
    timonwong
        3
    timonwong  
       2013-06-18 12:59:09 +08:00   ❤️ 1
    是否真正 Running 是可以由 VM/OS 决定的,打个比方,如果在GC阶段,需要暂停所有线程。但这个过程是透明的,所以Runnable 比 Running 意义上更加合理。
    Golevka
        4
    Golevka  
       2013-06-18 13:03:56 +08:00   ❤️ 1
    VM/OS会从若干runnable(ready)状态的线程中挑选一个运行, 所以处于ready状态的线程可能有许多, 而真正在运行线程的只有几个.

    waiting的线程不在ready queue里面, 如果没有被唤醒就不会被调度到的.
    andybest
        5
    andybest  
    OP
       2013-06-18 13:50:03 +08:00
    @timonwong 明白了,非常感谢!


    @Golevka 所以,由于ready queue的存在,一个状态为runnable的线程,实际上可能是并未在running对吗?
    Droog
        6
    Droog  
       2013-06-18 14:40:06 +08:00
    这个帖子比较有意义。
    之前一直没深究这个。
    Golevka
        7
    Golevka  
       2013-06-18 16:40:11 +08:00   ❤️ 1
    @andybest ready状态表示线程有被调度到的可能, 所以你可能会有好几十个ready的线程但是实际正在运行的只有一个.
    嘛, 反正我写kernel时喜欢把ready的线程放进ready queue单独管理, java里面可能没有等价物但是活动线程集的概念应该也是类似的.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5417 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 08:40 · PVG 16:40 · LAX 01:40 · JFK 04:40
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.