我习惯于在我的代码上运行FindBugs以查找错误或不良做法。今天它抱怨我在类构造函数中启动一个线程。
真的是一件坏事吗?你能解释一下为什么吗?
如果我的课程是最终的,至少是安全的吗?
编辑:
该线程被实现为一个内部类,它只使用在它启动时已经初始化的主类的字段:
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()
}
}
}
编辑:
我最后将线程的开始移动到 getInstance 方法,以避免引入未来错误的可能性:
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();
}
...