线程安全的单例模式

单例模式

  • 整个系统中,无论做怎样的业务操作,保证内存中只有一个对象实例。

单例是一种常见的软件设计模式,其核心思想是一个类只能有一个实例对象,由多个线程来共享该实例对象的资源。

public class Test{
	public static void main(String[] args) {
		for(int i=0;i<10;i++) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					Singleton singleton = Singleton.getInstance();
				}			
			}).start();		
		}
	}
}

class Singleton{
	private static Singleton instance = null;
	private Singleton() {
		System.out.println("创建单例对象");
	}
	public synchronized static Singleton getInstance() {
		if(instance == null) {
			instance = new Singleton();
		}
		return instance;
	}
}
package day_4_13;

public class Test {
	public static void main(String[] args) {
		for (int i = 0; i < 10; i++) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					Singleton singleton = Singleton.getInstance();
				}
			}).start();
		}
	}
}

class Singleton {
	private volatile static Singleton instance = null;

	private Singleton() {
		System.out.println("创建了Singleton对象");
	}

	public static Singleton getInstance() {
		if (instance == null) {
			synchronized (Singleton.class) {
				if (instance == null) {
					instance = new Singleton();
				}
			}
		}
		return instance;
	}
}
  • 数据是保存在主内存中的,线程在访问该数据时,并不是直接访问主内存中的数据,而是从主内存中拷贝出来一份数据放入工作内存中,线程对工作内存中的数据进行操作,操作完成之后再将工作内存中的数据拷贝到主内存中。
  • 使用volatile关键字来解决因 工作内存 -> 到主内存机制 导致可能发生的单例错误。
  • 使用volatile关键字修饰的变量,主内存对线程可见。

返回多线程目录

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值