Tamas Pataky
Tamas Pataky

Reputation: 363

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 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?

Upvotes: 5

Views: 631

Answers (4)

Paul Bellora
Paul Bellora

Reputation: 55223

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.

Upvotes: 0

Fredrik LS
Fredrik LS

Reputation: 1480

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

Upvotes: 0

Steve B.
Steve B.

Reputation: 57325

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();

Upvotes: 7

SLaks
SLaks

Reputation: 887797

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

Upvotes: 4

Related Questions