Why would anyone ever use the Java Thread no argument constructor?

那年仲夏 提交于 2021-02-05 04:54:24

问题


In what situation would anyone ever use the no-argument constructor of the Java Thread class? The API says:

This constructor has the same effect as Thread(null, null, gname), where gname is a newly generated name.

Correct me if I am wrong, but I think the target of the thread can not be modified after the new Thread object is instantiated. If the target equals null then the start method will do nothing right?

Why would you use this constructor?


回答1:


For one thing, it allows you to create subclasses without the PITA of explicitly calling the superclass constructor, e.g.

new Thread(){ 
   public void run() { ... }
}.start();



回答2:


If you make a (perhaps anonymou) class that inherits Thread and overrides run, your class needs to call this base constructor.




回答3:


If you inherit from Thread you certainly can use the no-arg constructor of Thread.




回答4:


Just to add to the other answers, this is the implementation of Java's Thread#run():

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

So you can see the effect is achieved one of two ways, either by providing a Runnable to a Thread constructor, so it is assigned to target, or by overriding this method in a subclass. If one does neither, a call to run() has no effect.



来源:https://stackoverflow.com/questions/7572527/why-would-anyone-ever-use-the-java-thread-no-argument-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!