单线程
public class Singleton
{
private static Singleton instance;
private Singleton() { }//私有实例构造器,如果自己不提供,编译器会自动生成共有无参构造器
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
多线程{
private static Singleton instance;
private Singleton() { }//私有实例构造器,如果自己不提供,编译器会自动生成共有无参构造器
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
class Multithread_singleton
{
private static volatile Multithread_singleton instance = null;//volatile保证代码不会被微调
private static object lockHeper = new object();
private Multithread_singleton() { }
public static Multithread_singleton Instance
{
get
{
if (instance == null)
{
lock (lockHeper)//double check 保证多线程不会同时进入
{
if (instance == null)
{
instance = new Multithread_singleton();
}
}
}
return instance;
}
}
}
{
private static volatile Multithread_singleton instance = null;//volatile保证代码不会被微调
private static object lockHeper = new object();
private Multithread_singleton() { }
public static Multithread_singleton Instance
{
get
{
if (instance == null)
{
lock (lockHeper)//double check 保证多线程不会同时进入
{
if (instance == null)
{
instance = new Multithread_singleton();
}
}
}
return instance;
}
}
}
浙公网安备 33010602011771号