[英]Will this onCreate() method always run after Foo() constructor?
我想这段代码是错误的,因为jvm可以选择在完成构造函数之前运行onCreate()
。
因此,当Foo()
构造函数完成时,如何确保onCreate()
将始终由另一个线程执行?
public class Foo{
public Foo(){
synchronized (this) {
new Thread(() -> {
synchronized (Foo.this) {
onCreate();
}
}).start();
}
}
protected void onCreate(){
}
}
使用静态工厂方法:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.