为什么C# 创建单例时需要双if加lock这种写法

 

public sealed class Singleton
    {
        private static Singleton instance;
        private static object locker = new object();
        private Singleton() { }
        public static Singleton GetInstance()
        {
            //if判断的作用是为了提高性能,没有这个if时,当多个线程同时执行到lock时,会导致线程阻塞等待
            if (instance==null)
            {
                //lock确保线程安全
                lock (locker)
                {
                    //if判断的作用在于保证只实例化一次
                    if (instance==null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
posted @ 2020-10-10 22:00  XCode_zhong  阅读(468)  评论(0)    收藏  举报