JAVA设计模式

设计模式汇总

1.双重锁单例模式

单例模式的应用:双重检查所机制DCL(double check lock)
public class Test{
    //为什么要用volatile关键字:因为在第一次初始化时,走到instance = new Test();时,进来N个线程,有了volatile就可以让他们不进入if(instance == null)里。
    public static volatile Test instance;
    public Test(){
    }
    public static Test sigle(){
        if(instance == null){
            synchronized(Test.class){
                //有可能其他线程在等待锁,所以要再次检查,否则就不是单例了。
                if(instance == null){
                    instance = new Test();
                }
            }
        }
        
        return instance;
    }
}
原文地址:https://www.cnblogs.com/chxwkx/p/14698231.html