user1420042
user1420042

Reputation: 1709

Is it possible to start a thread in Java from the object in its argument?

is it possible to do something like this in Java? I'm just wondering.

First, I just create a new thread that has one argument.

Thread thread = new Thread(new Person());

Then, in the constructor of Person() I would like to start that thread. So is something like this possible?

public Person() {
    // Here belongs some code for the constructor and then
    // I would like to start the thread
}

Upvotes: 0

Views: 56

Answers (3)

OldCurmudgeon
OldCurmudgeon

Reputation: 65811

Is this what you are looking for? Note the use of {start()} which avoids all of the issues with calling start in the constructor.

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

You can see the original here.

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

No, you can't. Before Java can call Thread() constructor it first has to eagerly evaluate all arguments, including call to Person() constructor. This means that by the time Person constructor is called, the outer Thread object doesn't even exist or was not yet initialized so you cannot really use it.

Upvotes: 2

SJuan76
SJuan76

Reputation: 24885

No.

You do not have the reference to the thread inside Person constructor. So, the thread still does not exist.

Even if you had it, doing something like

 public Person() {
   Thread a = new MyThread(this);
 }

is bad practice, because you are passing an instance (this) that might not have been fully initialized.

Upvotes: 1

Related Questions