java实现单例模式

懒汉式

线程不安全

public class Singleton {
    private Singleton() {};
    private static Singleton instance = null;
    public Singleton getInstace() {
        if(instance == null)
            instance = new Singleton;
        return instance;
    }
}

线程安全(双重检查锁)

public class Singleton {
    private Singleton() {};
    private static Singleton instance = null;
    public Singleton getInstace() {
        if(instance == null)   
          synchnorized(Singleton.class);
            if(instace == null)
                instance = new Singleton;
        return instance;
    }
}


饿汉式(线程安全)

public class Singleton2 {
    private Singleton() {};
    private static final Singleton instance = new Singleton2();//类加载便完成初始化
    public Singleton getInstance() {
        return instance;
    }
}

猜你喜欢

转载自blog.csdn.net/quitozang/article/details/80877013