首页 > 解决方案 > 当我调用 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 */
            }
        }
    }

标签: javamultithreading

解决方案


由于 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);
}

推荐阅读