DCL单例模式,用volatile关键创建

1. 单例模式

单例模式是一种常用的软件设计模式,其定义是单例对象的类只能允许一个实例存在。

单例模式的好处:
  1. 控制资源的使用,通过线程同步来控制资源的并发访问;
  2. 控制实例产生的数量,达到节约资源的目的。
  3. 作为通信媒介使用,也就是数据共享,它可以在不建立直接关联的条件下,让多个不相关的两个线程或者进程之间实现通信。
public class SingletonDemo {

	private static SingletonDemo singletonDemo;
	
	private SingletonDemo() {
		System.out.println(Thread.currentThread().getId() + "  SingletonDemo()执行!");
	}
	
	
	// 1. 可以加上 synchronized 保证线程安全 
	public static SingletonDemo instance() {
		if (singletonDemo == null) {
			singletonDemo = new SingletonDemo();
		}
		return singletonDemo;
	}
	
	public static void main(String[] args) {
		for (int i = 0; i < 10; i++) {
			new Thread(() -> {
				SingletonDemo.instance();
			}).start(); 
		}
	}
}

以上代码创建的单例是非线程安全的!!!可以加上 synchronized 关键字,但是高并发下会有阻塞的情况,不推荐使用。

public class SingletonDemo {

	private volatile static SingletonDemo singletonDemo;
	
	private SingletonDemo() {
		System.out.println(Thread.currentThread().getId() + "  SingletonDemo()执行!");
	}
	
	public static SingletonDemo instance() {
		if (singletonDemo == null) {
			synchronized (SingletonDemo.class) {
				if (singletonDemo == null) {
					singletonDemo = new SingletonDemo();
				}
			}
		}
		return singletonDemo;
	}
	
	public static void main(String[] args) {
		for (int i = 0; i < 10; i++) {
			new Thread(() -> {
				SingletonDemo.instance();
			}).start(); 
		}
	}
}

此处不加 volatile 可能线程不安全,因为有指令重排的情况,加入 volatile 可以禁止指令重排。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值