Android 线程同步 - synchronized 关键字不起作用?

Android Thread Synchronization - synchronized keyword doesn't work?

我正在为我的资源使用单例 class SingletonA,并且我有一个使用这些资源的服务 ServiceS。

public class SingletonA {
    private static SingletonA ourInstance = new SingletonA();
    public static SingletonA getInstance() { return ourInstance; }
    private SingletonA () {}

    String resources;

    synchronized public void importSomething() {
        resources = "I have some value now";
    }
}

public class ServiceS extends Handler {
    private static ServiceS ourInstance = new ServiceS();
    public static ServiceS getInstance() { return ourInstance; }
    private ServiceS () {}

    SingletonA sa = SingletonA.getInstance();

    public void printResources() {   
        println(sa.resources);
    }
}

public class MyActivity extends Activity {
    SingletonA sa = SingletonA.getInstance();

    @override
    protected void onCreateBundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        sa.importSomthing();            
        ServiceS.printResources();
    }
}

-> 在 ServicesS class 中,sa 值为 null -> sa.printResources() 导致 NPE

但是,因为我又添加了一个 sa = SingletonA.getInstance(); 到 ServiceS.printResources() 中,像这样:

public void printResources() {   
    sa = SingletonA.getInstance();
    println(sa);
}

-> 有效:sa != null 和资源 = "I have some value now"。 有人可以为我解释为什么 ServiceS 中的 sa 仍然为 null 吗?谢谢,

如好友评论:

这是由于静态初始化顺序。静态 ServiceS.ourService 在 SingletonA.ourInstance 之前初始化。

See here for more information on static initialization order。但简单的解决方案是在必要时调用 SingletonA.getInstance() (与在成员变量中缓存相比)。或者在 getInstance

中延迟初始化 ServiceS.ourInstance