Are Thread.sleep(0) and Thread.yield() statements equivalent?

后端 未结 12 1716
太阳男子
太阳男子 2020-11-27 02:42

Are these two statement equivalent?

Thread.sleep(0);
Thread.yield();
12条回答
  •  迷失自我
    2020-11-27 03:40

    OpenJDK source (Java SE 7) have the following implementation for Thread.sleep(0) in JVM_Sleep function of jvm.cpp:

      if (millis == 0) {
        // When ConvertSleepToYield is on, this matches the classic VM implementation of
        // JVM_Sleep. Critical for similar threading behaviour (Win32)
        // It appears that in certain GUI contexts, it may be beneficial to do a short sleep
        // for SOLARIS
        if (ConvertSleepToYield) {
          os::yield();
        } else {
          ThreadState old_state = thread->osthread()->get_state();
          thread->osthread()->set_state(SLEEPING);
          os::sleep(thread, MinSleepInterval, false);
          thread->osthread()->set_state(old_state);
        }
      }
    

    And implemtation of Thread.yield() have the following code:

      // When ConvertYieldToSleep is off (default), this matches the classic VM use of yield.
      // Critical for similar threading behaviour
      if (ConvertYieldToSleep) {
        os::sleep(thread, MinSleepInterval, false);
      } else {
        os::yield();
      }
    

    So Thread.sleep(0) and Thread.yield() may call same system calls in some platforms.

    os::sleep and os::yield are platform specific stuff. On both Linux and Windows: os::yield seems to be much simplier than os::sleep. For example: os::yield of Linux calls only sched_yield(). And os::sleep have about 70 lines of code.

提交回复
热议问题