java - 当我调用 Thread.start() 时如何调用 run() 方法?
问题描述
尽管有多个帖子解释了为什么我们应该直接调用start()
方法而不是run()
方法,但我的疑问更像是JDKrun()
在我调用时如何在内部调用方法start()
?
我浏览了Thread
类文件,但找不到run()
被调用的方法。它是从本机代码调用的吗?这是怎么回事?
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 是开源软件,因此您可以查看本机代码源。
例如Github 镜像Thread.c
类将Thread.start0()
本地方法定义为:
"start0", "()V", (void *)&JVM_StartThread},
where在源文件JVM_StartThread
中定义。jvm.cpp
如果您深入研究特定于操作系统的线程创建,您将到达从本机代码thread_entry()
中调用该方法的函数: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);
}
推荐阅读
- python - 如何生成唯一(!)均匀分布的随机数组/列表/序列
- c# - 类似于 RunWorkerCompleted 的 await/async 回调主线程
- android - android中的工具栏,折叠工具栏,应用栏,底部导航栏和操作栏有什么区别?
- php - 如何使用辅助类 WC_Product_Variation 正确创建 WooCommerce 变体
- r - acf() 函数绘制非常大的滞后
- docker - GKE 无法从 GCR 中提取图像
- php - CORS 问题 Angular + PHP REST API
- python - 必须调用 ray.init() 两次:第一次给出“AUTH
在没有为默认用户配置任何密码的情况下调用。” - sql - GitLab 管道错误:包 'mysql-client' 没有安装候选。我能做些什么?
- excel - 使用 vba 打开/保存 excel 文件时隐藏标准进度条