Possible Duplicate:
Java: Why not to start a thread in the constructor? How to terminate?
I m used to run FindBugs on my code in order to find bugs or bad practice. Today it complains on the fact that I m starting a thread in a class constructor.
真的不好吗 你能解释一下为什么吗
如果我的课是最后的,至少安全吗?
<强度 > EDIT 强度 > :
线条作为内部类执行, 它只使用主类开始时已经初始化的字段 :
public final class SingletonOuter {
private static SingletonOuter ourInstance = new SingletonOuter();
public static SingletonOuter getInstance() {
return ourInstance;
}
private final SomeOtherClass aField;
private SingletonOuter() {
aField=new SomeOtherClass();
thread=new InnerThread();
thread.start();
}
private boolean pleaseStop;
private synchronized boolean askedStop(){return pleaseStop;}
public synchronized void stop(){
pleaseStop=true;
}
private final InnerThread thread ;
private class InnerThread extends Thread{
@Override public void run() {
//do stuff with aField until askedStop()
}
}
}
<强度 > EDIT 强度 > :
避免未来引入错误的可能性:
public final class SingletonOuter {
private static SingletonOuter ourInstance
public static SingletonOuter getInstance() {
if (ourInstance==null){
ourInstance= = new SingletonOuter();
ourInstance.thread.start();
}
return ourInstance;
}
private final SomeOtherClass aField;
private SingletonOuter() {
aField=new SomeOtherClass();
thread=new InnerThread();
}
...