Java单例模式的三种线程安全版本

Double check

public class Singleton{
private static class SingletonHolder{
private static Singleton instance = new Singleton();
}
private Singleton(){}
public static Singleton newInstance(){
return SingletonHolder.instance;
}
}

静态内部类保证线程安全

public class Singleton {
private static volatile Singleton instance = null;
private Singleton() {
} public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
} } return instance;
}
}

枚举保证线程安全,也可防反射

public enum Singleton{
instance;
public void whateverMethod(){}
}

你可能感兴趣的:(Java,Java,基础)