懒汉式单例和双检锁/双重校验锁

懒汉式单例

public class Slingleton2{

    private static final Singleton2 instance = new Singleton2();

    private Singleton2(){}

    private static Singleton2 getlnstance(){
        return instance;
    }
}

双检锁/双重校验锁(DCL,即 double-checked locking)

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

你可能感兴趣的:(其他)