当前位置:网站首页>单例 DCL(double check lock) 饱汉模式和饿汉模式

单例 DCL(double check lock) 饱汉模式和饿汉模式

2022-08-09 06:29:00 史上最强的弟子

public class Test29 {

    public static void main(String[] args) {
        SingleObject singleObject = SingleObject.getSingleObject();
    }
}

//单例 饿汉模式
class SingleObject2{

    private static volatile SingleObject2 singleObject = new SingleObject2();

    private SingleObject2 (){}

    public static SingleObject2 getSingleObject(){
        return singleObject;
    }
}

//单例  饱汉模式
class SingleObject{

    private static volatile SingleObject singleObject;

    private SingleObject (){}

    //double Check lock
    public static SingleObject getSingleObject(){
        if(singleObject == null){
            synchronized (SingleObject.class){
                if(singleObject == null){
                        singleObject = new SingleObject();
                }
            }
        }
        return singleObject;
    }
}

 

原网站

版权声明
本文为[史上最强的弟子]所创,转载请带上原文链接,感谢
https://blog.csdn.net/sai739295732/article/details/114301064