线程安全的单例模式-求解疑
今天工作不怎么忙,想研究一下单例模式,由于前段时间在工作中用过(没用好,所以去掉了)因为当时对单例模式了解的不是很透彻。所以今天百度了一下单例的帖子,简直是发现了新大陆,除了我知道的传统饿汉式和懒汉式,还有帖子中讲线程安全的饿汉式,让我一脸懵逼,所以我特地发给帖子来请大佬们帮我证实一下,以免在工作中错误使用。
以下是我从各种帖子中看到的单例模式写法:
//饿汉式
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;
}
}
渴望大佬们解疑,灰常感谢!!!