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

时间:2015-08-12 16:12:56

标签: android multithreading synchronization thread-safety

我使用单例类SingletonA作为我的资源,我有一个使用资源的服务ServiceS。

--log-level=debug

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

但是,因为我将另外一个 sa = SingletonA.getInstance(); 添加到ServiceS.printResources()中,如下所示:

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();
    }
}

- > 有效:sa!= null和resources ="我现在有一些价值"。 有人可以解释为什么ServiceS中的sa仍然为空?谢谢,

1 个答案:

答案 0 :(得分:0)

作为Buddy的评论:

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

之前初始化

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