单例模式实现 Volitile , interlocked

时间:2021-10-06 18:33:20
         //单例模式:
//1. 双检锁机制 Volatile.write()
//2. 静态变量
//3. Interlocked.CompareExchange(ref single, temp, null); 模式 private static Singleton single = null;
private Singleton()
{
} public static Singleton GetSingleton()
{
if (single != null)
{
return single;
}
//多个线程可以创建对象,但是只有一个线程创建的能被赋值,其他的成为垃圾回收对象
Singleton temp = new Singleton();
//线程竞态,只有一个线程可以执行
Interlocked.CompareExchange(ref single, temp, null);
return single;
}
        private static Singleton2 instance = null;
private static object _lock = new object(); public static Singleton2 GetSingleton()
{
if (instance != null)
{
return instance;
} Monitor.Enter(_lock);
if(instance==null)
{
Singleton2 temp = new Singleton2();
//保证构造器在写入之前执行
Volatile.Write(ref instance,temp);
}
Monitor.Exit(_lock);
return instance;
}