本文介绍了扩展Thread类时如何调用run()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在浏览 java.lang.Thread 类的源代码时。奇怪的是我想看看Thread类如何调用 run()方法(用户定义的run())。当我实现 Runnable 界面时,如下所示

While going through the source code of java.lang.Thread class. Curiously I wanted to see how a run() method (user defined run()) is called by Thread class. when I am implementing Runnable interface as below

Thread waiterThread = new Thread(waiter, "waiterThread");
waiterThread.start();

上面的代码来自 Thread 类的构造函数正在调用 init()方法,并从那里开始将 Runnable 实例初始化为这个.target = target

In the above code from Thread class's constructor init() method is being called and from there itself they initialized the Runnable instance as this.target = target.

来自 start()他们正在调用的方法 native 方法 start0()这可能会反过来调用 run() Thread 类的方法,该方法导致用户定义的 run()方法执行。

from start() method they are calling a native method start0() which may in-turn call run() method of the Thread class which causes user defined run() method to execute.

以下是Thread类的 run()方法实现:

the following is the run() method implementation from Thread class:

 @Override
public void run() {
    if (target != null) {
        target.run();
    }
}

我的问题是我们延长 java.lang.Thread class,当我们调用 start()方法时,如下所示。

My question is when we extend java.lang.Thread class and when we call start() method as below.

public class HelloThread extends Thread {

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

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

 }

目标= null 在上面的例子中,设置target = HelloThread的实例是本机方法( start0())的责任吗?如果我扩展 Thread class?

target = null in the above case so is it the native method's (start0()) responsibility to set target=HelloThread's instance ? and how does a run() method of mine is called in case when I extend Thread class?

推荐答案

因为你扩展了课程。你覆盖run()方法来做一些不同的事情。 @Override注释用于突出显示此方法覆盖父方法。

Because you extended the class. You overrode the run() method to do something different. The @Override annotation is used to highlight that this method overrides a parent method.

目标未获得神奇地改变了,你在代码中忽略了。

The target doesn't get magically changed, you ignored in your code.

这篇关于扩展Thread类时如何调用run()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 22:06