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

前端 未结 3 1132
广开言路
广开言路 2020-12-11 13:07

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 Threa

相关标签:
3条回答
  • 2020-12-11 13:48

    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.

    0 讨论(0)
  • 2020-12-11 13:53
    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.

    0 讨论(0)
  • 2020-12-11 13:57

    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.

    0 讨论(0)
提交回复
热议问题