对于单例模式处理并发问题造成问题解决方法是:双重检查加锁
下面是Java和C#的写法
Java:
public class Singleton {
/**
* 对保存实例的变量添加volatile的修饰
*/
private volatile static Singleton instance = null;
private Singleton(){}
public static Singleton getInstance(){
//先检查实例是否存在,如果不存在才进入下面的同步块
if(instance == null){
//同步块,线程安全的创建实例
synchronized(Singleton.class){
//再次检查实例是否存在,如果不存在才真的创建实例
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
/**
* 对保存实例的变量添加volatile的修饰
*/
private volatile static Singleton instance = null;
private Singleton(){}
public static Singleton getInstance(){
//先检查实例是否存在,如果不存在才进入下面的同步块
if(instance == null){
//同步块,线程安全的创建实例
synchronized(Singleton.class){
//再次检查实例是否存在,如果不存在才真的创建实例
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
C#:
public class Singleton
{
private static object SingletonLoker = new object();
private static Singleton m_instance = null;
private Singleton()
{
}
public static Singleton getInstance()
{
if(m_instance==null)
{
lock(SingletonLoker)
{
if(m_instance==null)
{
m_instance=new Singleton();
}
}
}
return m_instance;
}
}
{
private static object SingletonLoker = new object();
private static Singleton m_instance = null;
private Singleton()
{
}
public static Singleton getInstance()
{
if(m_instance==null)
{
lock(SingletonLoker)
{
if(m_instance==null)
{
m_instance=new Singleton();
}
}
}
return m_instance;
}
}
具体详情请参略:
http://www.cnblogs.com/sjms/archive/2010/08/30/1812303.html
http://topic.csdn.net/u/20090811/09/7e6ee289-631d-410f-afd8-0eccd79c82dc.html