单例模式(Singleton):保证一个类仅有一个实例,并提供一个访问它的全局访问点。

1、多线程:lock是确保一个线程在临界区,另一个线程不能进入临界区。如果其他线程试图进入锁定的代码,它将一直等待。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 
 5 namespace Singleton
 6 {
 7     class Program
 8     {
 9         static void Main(string[] args)
10         {
11             Singleton s1 = Singleton.GetInstance();
12             Singleton s2 = Singleton.GetInstance();
13             if (s1 == s2)
14             {
15                 Console.WriteLine("两个对象相同");
16             }
17         }
18     }
19     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 }

相关文章:

  • 2021-09-08
  • 2022-01-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-19
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-16
  • 2021-12-05
  • 2022-02-18
  • 2021-12-12
相关资源
相似解决方案