Why not to start a thread in the constructor? How to terminate?
Solution 1:
To your first question: Starting a thread in a constructor passing in this
escapes this
. That means that you are actually giving out a reference to your object before it is fully constructed. The thread will start before your constructor finishes. This can result in all kinds of weird behaviors.
To your second question: There is no acceptable way to force another thread to stop in Java, so you would use a variable which the thread would check to know whether or not it should stop. The other thread would set it to indicate that the first thread would stop. The variable has to be volatile or all accesses synchronized to ensure proper publication. Here is some code which would be something like what you want.
public class MyNewThread implements Runnable {
private final Thread t;
private volatile boolean shouldStop = false;
MyNewThread() {
t = new Thread (this, "Data Thread");
}
public void start() {
t.start();
}
public void stop() {
shouldStop = true;
}
public void run() {
while(!shouldStop)
{
// do stuff
}
}
}
Whatever wants to create and start the thread would do:
MyNewThread thread = new MyNewThread();
thread.start();
Whatever wants to stop the thread would do:
thread.stop();
Solution 2:
Lets take a look at a basic example:
class MyClass implements Runnable{
int a = 0;
String b = null;
public MyClass(){
new Thread(this).start();
b = "Foo";
}
public void run(){
a = b.length(); //can throw NullPointerException
}
}
In this instance the MyClass.this is said to escape the constructor. That means that the object is available to reference but all of its fields that are being built in the constructor may not be created. To take this to another level what if b was final
You would expect it to be available but it is not ensured. This is known as a partially constructed objects and is perfectly legal in java.