簡體   English   中英

java Thread是否在系統中使用實時定時器或者它有自己的專用定時器?

[英]Is java Thread using Real time timer in system or it has it's own dedicated timer?

有沒有人知道Thread.sleep(1000)方法使用什么計時器? Thread是使用實時系統計時器還是擁有自己的專用計時器?

提前感謝您的回答。

Java語言規范將此方法的語義細節推遲到底層系統。 因此,行為將取決於您正在使用哪個JVM實現,以及可能還在運行應用程序的操作系統和硬件。

這就是JLS中的方法(第17章:線程和鎖)所說的全部內容:

17.9睡眠和產量

Thread.sleep導致當前正在執行的線程在指定的持續時間內休眠(暫時停止執行),具體取決於系統定時器和調度程序的精度和准確性 該線程不會失去任何監視器的所有權,並且恢復執行將取決於調度和執行該線程的處理器的可用性。

無論是零時間的睡眠還是屈服操作都不需要具有可觀察到的效果。

值得注意的是,Thread.sleep和Thread.yield都沒有任何同步語義。 特別是,編譯器不必在調用Thread.sleep或Thread.yield之前將寄存器中緩存的寫入刷新到共享內存,編譯器在調用Thread.sleep或Thread之后也不必重新加載緩存在寄存器中的值。讓。

Thread.sleep(long)是一種本機方法。 它的工作原理取決於操作系統和JVM的實現。

您可以在jvm.cpp [openjdk.java.net]中查看本機源代碼:

JVM_ENTRY(void, JVM_Sleep(JNIEnv* env, jclass threadClass, jlong millis))
  JVMWrapper("JVM_Sleep");

  if (millis < 0) {
    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
  }

  if (Thread::is_interrupted (THREAD, true) && !HAS_PENDING_EXCEPTION) {
    THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
  }

  // Save current thread state and restore it at the end of this block.
  // And set new thread state to SLEEPING.
  JavaThreadSleepState jtss(thread);

  HS_DTRACE_PROBE1(hotspot, thread__sleep__begin, millis);

  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);
    }
  } else {
    ThreadState old_state = thread->osthread()->get_state();
    thread->osthread()->set_state(SLEEPING);
    if (os::sleep(thread, millis, true) == OS_INTRPT) {
      // An asynchronous exception (e.g., ThreadDeathException) could have been thrown on
      // us while we were sleeping. We do not overwrite those.
      if (!HAS_PENDING_EXCEPTION) {
        HS_DTRACE_PROBE1(hotspot, thread__sleep__end,1);
        // TODO-FIXME: THROW_MSG returns which means we will not call set_state()
        // to properly restore the thread state.  That's likely wrong.
        THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
      }
    }
    thread->osthread()->set_state(old_state);
  }
  HS_DTRACE_PROBE1(hotspot, thread__sleep__end,0);
JVM_END

在上面的代碼中,它調用操作系統的sleep功能。

來自javadoc

導致當前正在執行的線程休眠(暫時停止執行)指定的毫秒數,具體取決於系統計時器和調度程序的精度和准確性。 該線程不會失去任何監視器的所有權。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM