单例模式-懒汉式

/**
懒汉式
volatile 防止指令重排序
1 分配空间
2 引用赋值
3 初始化操作
*/
public class LazySingleton {
private static volatile LazySingleton lazySingleton;
private LazySingleton() {
}

public static LazySingleton getInstance() {
if (lazySingleton == null) {
synchronized (LazySingleton.class) {
// 这里加判断是防止还未new对象的时候另一个线程进入到前面的那个if判断里面, 这样就会导致创建2份对象
if (lazySingleton == null) {
lazySingleton = new LazySingleton();
}
}
}
return lazySingleton;
}
}

public class Test {
public static void main(String[] args) {
new Thread(() -> {
LazySingleton instance1 = LazySingleton.getInstance();
// com.example.SpringBootTest1.shejimoshi.singleton.LazySingleton@6a51da45
System.out.println(instance1);
}).start();

new Thread(() -> {
LazySingleton instance2 = LazySingleton.getInstance();
// com.example.SpringBootTest1.shejimoshi.singleton.LazySingleton@6a51da45
System.out.println(instance2);
}).start();
}
}


posted @   剑阁丶神灯  阅读(37)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示