1 //单例模式: 2 //1. 双检锁机制 Volatile.write() 3 //2. 静态变量 4 //3. Interlocked.CompareExchange(ref single, temp, null); 模式 5 6 private static Singleton single = null; 7 private Singleton() 8 { 9 } 10 11 public static Singleton GetSingleton() 12 { 13 if (single != null) 14 { 15 return single; 16 } 17 //多个线程可以创建对象,但是只有一个线程创建的能被赋值,其他的成为垃圾回收对象 18 Singleton temp = new Singleton(); 19 //线程竞态,只有一个线程可以执行 20 Interlocked.CompareExchange(ref single, temp, null); 21 return single; 22 }
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; }