C#单例模式的2种实现方式,Lazy模式和双检锁模式

 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     }

打印出的结果

 

posted on 2020-10-10 14:18  Shine-Zhong  阅读(1303)  评论(0编辑  收藏  举报

导航