java 两种线程安全的单例

2017-02-12  本文已影响0人  Tonki

一、 volatile和双检锁

public class EventBus {

    //volatile 保证了各个线程的得到的defaultInstance都是最新的
    static volatile EventBus defaultInstance;

    /** Convenience singleton for apps using a process-wide EventBus instance. */
    public static EventBus getDefault() {
        if (defaultInstance == null) {
            synchronized (EventBus.class) {
                if (defaultInstance == null) {//进入同步块后再次判断最新的defaultInstance
                    defaultInstance = new EventBus();
                }
            }
        }
        return defaultInstance;
}

二、 利用静态内部类

public class HttpMethods {

    private HttpMethods(){};

    private static class SingletonHolder{
        private static final HttpMethods INSTANCE = new HttpMethods();
    }

    //获取单例
    public static HttpMethods getInstance(){
        //实例为静态类的静态变量
        return SingletonHolder.INSTANCE;
    }
}
上一篇下一篇

猜你喜欢

热点阅读