我对 Application 的子类使用单例方法。我使用以下内容:
public class MyApplication extends Application {
private static MyApplication instance;
public MyApplication() {
instance = this;
}
public static MyApplication getInstance() {
if (instance == null) {
synchronized (MyApplication.class) {
if (instance == null)
new MyApplication();
}
}
return instance;
}
...
...
我的问题是:如果实例被分配一次,在系统对类创建者的初始调用期间,该实例永远不应为空!所以if (instance == null)
insidegetInstance()
永远不会返回 true。还是我错了?
编辑:
我更正了维基百科上的代码:
public class volatile MyApplication extends Application {
private static MyApplication instance;
public MyApplication() {
}
public static MyApplication getInstance() {
if (instance == null) {
synchronized (MyApplication.class) {
if (instance == null)
instance = new MyApplication();
}
}
return instance;
}
...
...
添加volatile
并且instance = new MyApplication();
正确吗?我的问题仍然存在...