线程安全的单例模式-求解疑

线程安全的单例模式-求解疑

今天工作不怎么忙,想研究一下单例模式,由于前段时间在工作中用过(没用好,所以去掉了)因为当时对单例模式了解的不是很透彻。所以今天百度了一下单例的帖子,简直是发现了新大陆,除了我知道的传统饿汉式和懒汉式,还有帖子中讲线程安全的饿汉式,让我一脸懵逼,所以我特地发给帖子来请大佬们帮我证实一下,以免在工作中错误使用。

以下是我从各种帖子中看到的单例模式写法:

//饿汉式
public class Testc{
	private Testc(){}
	private static Testc instance = new Testc();
	public static Testc getInstance(){
		return instance;
	}
}
//懒汉式
public class Testc{
	private Testc(){}
	private static Testc instance = null;
	public static Testc getInstance(){
		if(null == instance){
			instance = new Testc();
		}
		return instance;
	}
}
//采用内部类实现的饿汉式
public class Testc{
	private Testc(){}
	private static Testc instance = null;
	private static class TestcProcess{
		public static Testc instance= new Testc();
	}
	public static Testc getInstance(){
		return TestcProcess.instance;
	}
}

下面这样看着较为像实际案例,
按文中楼主讲的意思是,比如同时有两个线程调用getInstance()方法,p1检测instance为空,则实例化对象,在p1实例化之前p2处于等待状态,p1 new完以后返回了对象实例,p2再进去讲不会再new对象,所以保证了线程安全。

//具有双重验证的懒汉式
public class Testc{
	private Testc(){}
	private static volatile Testc instance = null;
	
	public static Testc getInstance(){
		if(null == instance ){
			synchronized (Testc.class){
				if(null == instance){
					instance = new Testc();
				}
			}
		}
		return instance;
	}
}

渴望大佬们解疑,灰常感谢!!!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值