what is the logic behind the Thread.sleep() in java
Anybo开发者_StackOverflowdy know ,what is the logic behind Thread.sleep in java? . Are they using timer
Well, you can also take a look here http://openjdk.java.net. For ver. 7 there is some interesting code in jvm.cpp:
JVM_ENTRY(void, JVM_Sleep(JNIEnv* env, jclass threadClass, jlong millis))
JVMWrapper("JVM_Sleep");
if (millis 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) {
// 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);
}
JVM_END
The "logic behind" the Thread.sleep()
in the sense that you appear to be asking will be implemented in the operating system kernel or system libraries.
As such, the "logic" may vary from operating system. For an open source OS such as Linux, BSD or OpenSolaris, you could delve into the OS source code to figure this out. For a closed source OS, you may need to resort to reverse engineering.
Either way, the implementation "logic" (e.g. whether it uses a timer or not) may differ from operating system to operating system and from OS version to OS version.
If by "logic" you mean "how is Thread.sleep()
implemented internally", it's a native method, which means it's dependent on the platform and JVM implementation. I would expect most implementations rely on the threading mechanism made available from the underlying operating system.
精彩评论