我认为这段代码是错误的,因为jvm可以在完成构造函数之前选择运行onCreate()
。
那么,当onCreate()
构造函数完成时,如何确保Foo()
始终由另一个线程执行?
public class Foo{
public Foo(){
synchronized (this) {
new Thread(() -> {
synchronized (Foo.this) {
onCreate();
}
}).start();
}
}
protected void onCreate(){
}
}
答案 0 :(得分:2)
使用静态工厂方法:
public class Foo {
// Private constructor forces instances to be created using factory method.
private Foo() {}
protected void onCreate() {}
static Foo newInstance() {
Foo foo = new Foo();
new Thread(foo::onCreate).start();
return foo;
}
}