gpt4 book ai didi

java - java `wait()`等待是如何实现的?

转载 作者:行者123 更新时间:2023-12-01 17:46:49 25 4
gpt4 key购买 nike

我问的是等待过程,而不是访问排序方法,它是最简单的形式,是带有条件退出的无限循环。

等待请求的资源消耗最少的方式是什么,这就是我问这个问题的原因。

最佳答案

Object.wait()功能是通过 JVM_MonitorWait native 方法实现的,按照 ThreadReference javadoc:

/** Thread is waiting - Object.wait() or JVM_MonitorWait() was called */
public final int THREAD_STATUS_WAIT = 4;

该方法的实现可以参见jvm.cpp并使用 ObjectSynchronizer::wait:

JVM_ENTRY(void, JVM_MonitorWait(JNIEnv* env, jobject handle, jlong ms))
JVMWrapper("JVM_MonitorWait");
Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
JavaThreadInObjectWaitState jtiows(thread, ms != 0);
if (JvmtiExport::should_post_monitor_wait()) {
JvmtiExport::post_monitor_wait((JavaThread *)THREAD, (oop)obj(), ms);

// The current thread already owns the monitor and it has not yet
// been added to the wait queue so the current thread cannot be
// made the successor. This means that the JVMTI_EVENT_MONITOR_WAIT
// event handler cannot accidentally consume an unpark() meant for
// the ParkEvent associated with this ObjectMonitor.
}
ObjectSynchronizer::wait(obj, ms, CHECK);
JVM_END

ObjectSynchronizer::wait 实现位于 synchronizer.cpp并委托(delegate)给 objectMonitor.cpp 中的 ObjectMonitor::wait

如果您继续深入研究,您最终将到达依赖于平台的 native Java 线程实现。在 Linux 上,这将是 libpthread.so ,它将最终处理线程状态更改。

关于java - java `wait()`等待是如何实现的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54265523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com