懒汉式【单例模式】

目录

懒汉式

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

上述懒汉式会有线程安全问题
优化

public class Singleton{
	private Singleton(){
	}
	//保证可见性,防止指令重排
	private volatile static Singleton singleton = null;
	public static Singleton getSingleton(){
	//提升效率,对象已经存在就不再加锁判断
		if(singleton == null){
		//加同步锁
			synchronized (Singleton.class){
			//检查对象是否存在,不存在创建对象
				if(singleton == null){
					singleton = new Singleton();
				}
			}
		}
		return singleton;
	}
}

相关推荐

  1. 懒汉模式

    2024-03-23 08:10:04       19 阅读
  2. 设计模式-模式懒汉

    2024-03-23 08:10:04       20 阅读
  3. 如何理解模式---懒汉

    2024-03-23 08:10:04       30 阅读
  4. 2_单列模式_懒汉模式

    2024-03-23 08:10:04       36 阅读
  5. C++设计模式模式(饿汉懒汉

    2024-03-23 08:10:04       40 阅读
  6. 模式---饿汉模式懒汉模式

    2024-03-23 08:10:04       18 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-23 08:10:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-23 08:10:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-23 08:10:04       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-23 08:10:04       20 阅读

热门阅读

  1. 设计模式(行为型设计模式——状态模式)

    2024-03-23 08:10:04       17 阅读
  2. 【PHP】通过PHP开启/暂停Apache、MySQL或其他服务

    2024-03-23 08:10:04       21 阅读
  3. OpenCV基于阈值的分割技术详细介绍

    2024-03-23 08:10:04       19 阅读
  4. 数仓建模架构—Inmon范式建模与Kimball维度建模

    2024-03-23 08:10:04       21 阅读
  5. LeetCode //C - 75. Sort Colors

    2024-03-23 08:10:04       19 阅读
  6. 【LeetCode-153.寻找旋转排序数组的最小值】

    2024-03-23 08:10:04       22 阅读
  7. DDD中如何识别子域、实体、值对象和聚合

    2024-03-23 08:10:04       19 阅读
  8. 解决微信小程序页面数量限制问题的6种方法

    2024-03-23 08:10:04       76 阅读
  9. 微信小程序实现图片懒加载的4种方案

    2024-03-23 08:10:04       15 阅读
  10. mapbox 获取当前比例尺 scale

    2024-03-23 08:10:04       18 阅读
  11. npm run lint 格式化问题

    2024-03-23 08:10:04       20 阅读