MaheshVarma
MaheshVarma

Reputation: 2125

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?

Upvotes: 1

Views: 8025

Answers (3)

user1668782
user1668782

Reputation: 189

In start() method- underlying runtime object run() method is going to get called within start() method. And here underlying runtime object is HelloThread class object. Thats why run() method of HelloThread is called.

Upvotes: 0

Aniket Thakur
Aniket Thakur

Reputation: 68935

new HelloThread()

itself will call the init() method which will set your target. It will be set to null in case you are extending Thread class. So target will be null.

If you see docs for run() method it clearly says

If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.Subclasses of Thread should override this method.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533510

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.

Upvotes: 1

Related Questions