Why would anyone ever use the Java Thread no argument constructor?
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开发者_如何学JAVA 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?
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();
If you make a (perhaps anonymou) class that inherits Thread
and overrides run
, your class needs to call this base constructor.
If you inherit from Thread you certainly can use the no-arg constructor of Thread.
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.
精彩评论