双重检查锁(double checked locking)
只在第一次调用getInstance时, 进行同步加锁
public class DclSingleton{
private DclSingleton(){}
private static volatile DclSingleton instance = null;
public static DclSingleton getInstance(){
if (instance == null){
synchronized(DclSingleton.class){
if (instance == null) {
instance = new DclSingleton();
}
}
}
return instance;
}
}
静态内部类实现
class Singleton2{
private Singleton2(){}
private static class innerClass{
private static Singleton2 instance =new Singleton2();
}
public static Singleton2 getInstance(){
return innerClass.sa;
}
}
枚举
enum Singleton3{
instance;
}