几种单例模式的思考

DCL(Double Check Lock,双重检查锁)机制

public class Singleton {
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if (instance==null){
instance = new Singleton();
}
return instance;
}
}
public class Singleton {
private static Singleton instance = null;
private Singleton(){}
public synchronized static Singleton getInstance(){
if (instance==null){
instance = new Singleton();
}
return instance;
}
}
public class Singleton {
private static Singleton instance = null;
private Singleton(){}
public static Singleton getInstance(){
if (instance==null){
synchronized (Singleton.class){
if (instance == null)
instance = new Singleton();
}
}
return 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 class Singleton {
private static class Singletonholder{
private static final Singleton instance = new Singleton();
private Singletonholder(){}

}
private Singleton(){}
public synchronized  static Singleton getInstance(){
    return Singletonholder.instance;
}

}

你可能感兴趣的:(几种单例模式的思考)