标签:
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 5 namespace 单例模式 6 { 7 public class Program 8 { 9 static void Main(string[] args) 10 { 11 Singleton s1 = Singleton.GetInstance(); 12 Singleton s2 = Singleton.GetInstance(); 13 14 if (s1 == s2) 15 { 16 Console.WriteLine("Objects are the same instance"); 17 } 18 19 Console.Read(); 20 } 21 } 22 23 public class Singleton 24 { 25 private static readonly Singleton instance = new Singleton(); 26 private Singleton() { } 27 public static Singleton GetInstance() 28 { 29 return instance; 30 } 31 } 32 }
1 namespace 单例模式 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 Singleton s1 = Singleton.GetInstance(); 8 Singleton s2 = Singleton.GetInstance(); 9 10 if (s1 == s2) 11 { 12 Console.WriteLine("Objects are the same instance"); 13 } 14 15 Console.Read(); 16 } 17 } 18 19 public class Singleton 20 { 21 private static Singleton instance; 22 private static readonly object syncRoot = new object(); 23 private Singleton() 24 { 25 } 26 27 public static Singleton GetInstance() 28 { 29 lock (syncRoot) 30 { 31 if (instance == null) 32 { 33 instance = new Singleton(); 34 } 35 } 36 return instance; 37 } 38 } 39 }
这个例子能不能保证多线程安全呢?能。最先进入的那个线程会创建对象实例,保证类只实例化一次。但这样每次都lock的话,一旦多次调用时,第一个调用的会进入lock,而其他的线程则需要等待第一个结束才能依次调用,后面的依次调用,等待......所以会导致性能损耗。lock加锁就好比漏斗一样,每次只能样一个线程通过
1 namespace 单例模式 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 Singleton s1 = Singleton.GetInstance(); 8 Singleton s2 = Singleton.GetInstance(); 9 10 if (s1 == s2) 11 { 12 Console.WriteLine("Objects are the same instance"); 13 } 14 15 Console.Read(); 16 } 17 } 18 19 public class Singleton 20 { 21 private static Singleton instance; 22 private static readonly object syncRoot = new object(); 23 private Singleton() 24 { 25 } 26 27 public static Singleton GetInstance() 28 { 29 if (instance == null) 30 { 31 lock (syncRoot) 32 { 33 if (instance == null) 34 { 35 instance = new Singleton(); 36 } 37 } 38 } 39 return instance; 40 } 41 } 42 }
1 namespace 单例模式 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 Singleton s1 = Singleton.GetInstance(); 8 Singleton s2 = Singleton.GetInstance(); 9 10 if (s1 == s2) 11 { 12 Console.WriteLine("Objects are the same instance"); 13 } 14 15 Console.Read(); 16 } 17 } 18 19 public sealed class Singleton 20 { 21 private static readonly Singleton instance = new Singleton(); 22 private Singleton() 23 { 24 } 25 26 public static Singleton GetInstance() 27 { 28 return instance; 29 } 30 } 31 }
标签:
原文地址:http://www.cnblogs.com/Hugh621/p/5820257.html