There is nothing wrong with passing this
to a thread constructor. I suspect that what you are referring to is passing this
to a thread constructor, in your own constructor.
class MyClass implements Runnable {
private final Integer value;
MyClass() {
new Thread(this);
int i = 0;
value = Integer.valueOf(20 / i);
}
@Override
public void run() {
System.out.println(value.intValue());
}
}
In general it's a bad idea to "leak" a this
-reference from your constructor, because if the constructor throws an exception, the object may be left in an inconsistent state.
More specifically, it's a bad idea to start a thread with this
in the constructor, because the thread may start running before you have finished constructing your object. So, even if i
was 1 above, run()
might still throw because it might happen before value
was assigned.
In some cases you can kludge around this by creating the thread in the last line of your constructor. But this is not foolproof, since that constructor might be called by a superclass. A better solution is:
class MyClass implements Runnable {
...
MyClass start() {
new Thread(this);
return this;
}
...
}
// Then construct like this:
MyClass foo = new MyClass().start();