Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

java - How a run() method is called when we extend Thread class

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();

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.

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.

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

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

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();
   }

 }

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

how does a run() method of mine is called in case when I extend Thread class

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...