- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- namespace SingletonPattern
- {
- /// <summary>
- /// 私有化构造函数
- /// 私有的静态变量
- /// 一个静态的对象创建方法
- /// </summary>
- public class Singleton
- {
- private Singleton()//构造函数私有
- {
- Console.WriteLine("初始化了?但我只能被掉一次哦,线程id={0}",Thread.CurrentThread.ManagedThreadId);
- }
- private staticSingleton _Singleton =null;
- private static objectSingleton_Lock =new object();
- public static Singleton CreateInstance() //双null
- {
- if(_Singleton ==null)//保证对象初始化之后的所有线程,不需要等待锁
- {
- Console.WriteLine("准备进入lock");
- lock(Singleton_Lock)//保证只有一个线程进去判断
- {
- //Thread.Sleep(1000);
- if(_Singleton ==null)//保证对象为空才真的创建
- {
- _Singleton =new Singleton();
- }
- }
- }
- return _Singleton;
- }
- public void Show()
- {
- Console.WriteLine("这里调用了{0}.Show", this.GetType().Name);
- }
- }
- }
来源: http://www.bubuko.com/infodetail-1949261.html