gpt4 book ai didi

java - 当我调用 Thread.start() 时,如何调用 run() 方法?

转载 作者:行者123 更新时间:2023-12-01 19:32:14 25 4
gpt4 key购买 nike

尽管有多个帖子解释了为什么我们应该调用 start()方法而不是 run()直接方法我的疑问更像是JDK如何调用run()当我调用 start() 时内部方法?

我浏览了Thread类文件,我找不到 run()方法被调用。它是从 native 代码调用的吗?这是怎么发生的?

public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();

/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);

boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}

最佳答案

由于 OpenJDK 是开源软件,因此您可以看到 native 代码源。

例如Github mirror of Thread.c类将 Thread.start0() native 方法定义为:

"start0",           "()V",        (void *)&JVM_StartThread},

其中 JVM_StartThread 定义于 jvm.cpp源文件。

如果您深入研究特定于操作系统的线程创建,您将到达 thread_entry()从 native 代码中调用 Thread.run() 方法的函数:

static void thread_entry(JavaThread* thread, TRAPS) {
HandleMark hm(THREAD);
Handle obj(THREAD, thread->threadObj());
JavaValue result(T_VOID);
JavaCalls::call_virtual(&result,
obj,
SystemDictionary::Thread_klass(),
vmSymbols::run_method_name(),
vmSymbols::void_method_signature(),
THREAD);
}

关于java - 当我调用 Thread.start() 时,如何调用 run() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59287048/

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