DCL单例模式:单例+多线程

/*
DCL单例模式 懒汉式 在多线程环境下 对外存在一个对象
构造器私有化
提供私有的静态属性
提供公共的静态方法 获取属性
*/
public class LazyMan
{
//提供私有的静态属性 解决指令重排
private static volatile LazyMan instance;
    //构造器私有化
private DoubleCheckedLocking(){

}
//提供一个公有方法创建对象
public static
LazyMan getInstance(){
        //再次检测
if (null != instance) {
return instance;
}
synchronized (
LazyMan.class) {
            if (null == instance) {
instance = new
LazyMan();
                //1。开辟空间 2,初始化对象信息 3。返回对象的地址给引用
}
}
return instance;
}
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println(
LazyMan.getInstance());
        });
thread.start();
System.out.println(
LazyMan.getInstance());
    }
}
posted @ 2021-08-24 15:55  下饭  阅读(73)  评论(0编辑  收藏  举报