1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading; 6 7 namespace _01单例模式演示 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 14 //for (int i = 0; i < 100; i++) 15 //{ 16 // Person p = new Person(); 17 18 // Person p1 = new Person(); 19 //} 20 21 //Person p = new Person( 22 23 //for (int i = 0; i < 1000; i++) 24 //{ 25 // Person p = Person.GetInstance(); 26 //} 27 28 for (int i = 0; i < 1000; i++) 29 { 30 31 Thread t = new Thread(new ThreadStart(() => 32 { 33 //Person p = Person.GetInstance(); 34 //Singleton p = Singleton.GetInstance(); 35 36 Singleton2 s2 = Singleton2.GetInstance(); 37 })); 38 t.Start(); 39 } 40 Console.WriteLine("ok"); 41 Console.Read(); 42 43 44 45 46 47 } 48 } 49 50 51 //利用静态字段,在第一次使用类的时候只初始化一次的特性。 52 public class Singleton2 53 { 54 private Singleton2() 55 { 56 Console.WriteLine("."); 57 } 58 private static readonly Singleton2 _instance = new Singleton2(); 59 60 public static Singleton2 GetInstance() 61 { 62 return _instance; 63 } 64 } 65 66 67 68 69 70 71 72 public class Singleton 73 { 74 private Singleton() 75 { 76 Console.WriteLine("."); 77 } 78 79 private static Singleton _instance; 80 81 private static readonly object syn = new object(); 82 83 public static Singleton GetInstance() 84 { 85 //lock (syn) 86 //{ 87 // if (_instance == null) 88 // { 89 // _instance = new Singleton(); 90 // } 91 // return _instance; 92 //} 93 if (_instance == null) 94 { 95 lock (syn) 96 { 97 if (_instance == null) 98 { 99 _instance = new Singleton(); 100 } 101 102 } 103 } 104 return _instance; 105 106 } 107 } 108 109 110 111 112 public class Person 113 { 114 115 //把类的构造函数的访问修饰符改为private 116 private Person() 117 { 118 Console.WriteLine("."); 119 } 120 121 private static Person _instance = null; 122 123 public static Person GetInstance() 124 { 125 if (_instance == null) 126 { 127 _instance = new Person(); 128 } 129 return _instance; 130 } 131 132 133 public string Name { get; set; } 134 public string Email { get; set; } 135 public int Age { get; set; } 136 } 137 }