1 using System;
2 using System.Threading;
3
4 namespace Singleton
5 {
6 class Program
7 {
8 static void Main(string[] args)
9 {
10 Singleton s1 = Singleton.CreateInstance();
11 Singleton s2 = Singleton.CreateInstance();
12 Console.WriteLine(s1 == s2);
13 Console.ReadKey();
14 }
15 }
16
17 class Singleton
18 {
19 private static Singleton instance;
20 private Singleton() { }//私有构造函数,防止实例化
21 private static object obj = new object();//通过Lock关键字实现同步
22 public static Singleton CreateInstance()
23 {
24 if (instance == null)
25 {
26 lock (obj)
27 {
28 if (instance == null)
29 {
30 instance = new Singleton();
31 }
32
33 }
34 }
35 return instance;
36 }
37
38 }
39 }