哪个方法调用run()? [英] Which method calls run()?

查看:53
本文介绍了哪个方法调用run()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class HelloRunnable implements Runnable {

public void run() {
    System.out.println("Hello from a thread!");
}

public static void main(String args[]) {
    (new Thread(new HelloRunnable())).start();
} } 

根据 Java文档

Runnable 接口定义了一个单一方法 run ,旨在包含在线程中执行的代码.将Runnable对象传递给Thread构造函数.

The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor.

那么,当我们执行HelloRunnable时,谁调用了内部运行方法? Thread 类中, start 方法如下所示:

So, When we execute HelloRunnable, who calls the inside run method? In the Thread class, the start method looks like this:

public synchronized void start() {
     if (threadStatus != 0)
         throw new IllegalThreadStateException();
     group.add(this);
     start0();
     if (stopBeforeStart) {
         stop0(throwableFromStop);
     }
 }

从这段代码中,我们可以看到start方法没有调用 run()方法.

From this code, we can see that the start method is not calling the run() method.

推荐答案

Java虚拟机调用此线程的 run 方法

因此,正是JVM的 start0 中的本机代码负责在新创建的线程中调用 run .(这并不出乎意料,因为启动线程是特定于操作系统的,并且无法用纯Java实现.)

So, it is the native code in start0 of the JVM that takes care of calling run in the newly created thread. (This is not quite unexpected, as launching a thread is very OS-specific and cannot be implemented in pure Java.)

注意: start0 不会直接调用 run .取而代之(在高级视图中,它忽略了JVM的内部管理),它指示操作系统创建一个新线程,并让该线程执行 run .

Note: start0 does not call run directly. Instead (on a high-level view, ignoring JVM-internal management), it instructs the operating system to create a new thread and let that thread execute run.

请澄清一下,这里是有关方法的简短说明:

Just to clarify, here is a short description of the involved methods:

  • start 是用于启动新的 Thread 的高级功能.

  • start is the high-level function to start a new Thread.

start0 是从操作系统创建新线程的本机方法,负责确保调用 run .

start0 is the native method which creates a new Thread from the operating system and is responsible to ensure that run is called.

run 是在 Runnable 类中定义的方法.此方法将在新线程中执行.Java本身中的 Thread 对象本身并不知道应执行的用户代码.这是关联的 Runnable 对象的职责.

run is the method defined in your Runnable classes. This method is what will be executed in the new thread. A Thread object in Java itself has no idea about the user code it should execute. This is the responsibility of the associated Runnable object.

因此,当您调用 Thread.start()时,将自动调用 Runnable run 方法.

Thus, when you call Thread.start(), the run method of the Runnable will automatically be called.

当然,您总是可以显式调用 Runnable run 方法:

Of course, you can always call the run method of a Runnable explicitly:

HelloRunnable hr = new HelloRunnable();
hr.run();

但是,这当然不会 在单独的线程中执行,但是会阻止执行.

However, this will, of course, not be executed in a separate thread, but block the execution.

这篇关于哪个方法调用run()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆