1 public class MyClass 2 { 3 //volatile 關鍵字指示一個字段可以由多同時執行的線程修改。 聲明為 volatile 的字段不受編譯器優化(假定由單個線程訪問)的限制。 這樣可以確保該字段在任何時間呈現的都是最新的值。 4 private static volatile MyClass _instance; 5 private static readonly object InstanceLock = new object(); 6 public static MyClass Instance 7 { 8 get 9 { 10 if (_instance == null) 11 { 12 lock (InstanceLock) 13 { 14 if (_instance != null) 15 { 16 return _instance; 17 } 18 _instance = new MyClass(); 19 } 20 } 21 22 return _instance; 23 } 24 } 25 26 //在.NET 中這種模式已用 Lazy<T>類實現了封裝,內部就是使用了雙檢鎖模式。 你最好還是使用 Lazy<T>,不要去實現自己的雙檢鎖模式了。這樣非常的簡潔 27 public static MyClass Instance2 = new Lazy<MyClass>(() => new MyClass()).Value; 28 } 29 30 class Program 31 { 32 33 34 static void Main(string[] args) 35 { 36 for (int i = 0; i < 10; i++) 37 { 38 Thread th = new Thread(() => { Console.WriteLine("線程調用對象{0}", MyClass.Instance.GetHashCode()); }); 39 th.Start(); 40 } 41 for (int i = 0; i < 10; i++) 42 { 43 Thread th = new Thread(() => { Console.WriteLine("線程調用對象{0}", MyClass.Instance2.GetHashCode()); }); 44 th.Start(); 45 } 46 47 Console.ReadLine(); 48 } 49 50 }
打印出的結果