问题
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