It is said threads should NEVER be started in constructors, but I am not sure how this reference escapes the Test constructor in this case. I looked at the underlying Thread.java and I cannot figure this out.
class Test {
static MyThread thread;
public Test() {
thread = new MyThread();
thread.start();
}
}
class MyThread extends Thread {
public void run() {
//do stuff
}
}
Thanks for the help.
thread = new MyThread(); would call Thread super constructor:
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
I do not see a reference getting away.
thiscan only escape if the thread referencesthis(eg, if it’s an inner class)Your thread does not reference
this, so this is not an issue.However, constructing an object is generally expected to be side-effect-free; this is not a good idea.