zoukankan      html  css  js  c++  java
  • 单例模式

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

    结构图:

    image

     //单线程

        class Singleton
        {
            private static Singleton instance;

            private Singleton()
            { }

            public static Singleton GetInstance()
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
     
    //多线程
        class Singleton2
        {
            private static Singleton2 instance;
            private static readonly object synvRoot = new object();

            private Singleton2()
            { }

            public static Singleton2 GetInstance()
            {
                if (instance == null)
                {
                    lock (synvRoot)
                    {
                        if (instance == null)
                        {
                            instance = new Singleton2();
                        }
                    }
                }
                return instance;
            }

            //线程【串行化】的方式睡眠了 20 毫秒
            public static void ddd()
            {
                lock (synvRoot)
                    System.Threading.Thread.Sleep(20);
            }
        }
     

     主函数:

        class Program
        {
            static void Main(string[] args)
            {
                Singleton s1 = Singleton.GetInstance();
                Singleton s2 = Singleton.GetInstance();
                if (s1 == s2)
                {
                    Console.WriteLine("s1和s2是相同实例");
                }

                //多线程
                Singleton2 s3 = Singleton2.GetInstance();
                Singleton2 s4 = Singleton2.GetInstance();
                if (s3 == s4)
                {
                    Console.WriteLine("s1和s2是相同实例");
                }

                Console.ReadKey();
            }
        }

    Lock是确保当一个线程位于代码的临界区时,另一个线程不进入临界区,如果其他线程试图进入锁定的代码,侧他将一直等待,直到被该对象释放。

  • 相关阅读:
    BZOJ4821 SDOI2017相关分析(线段树)
    BZOJ3167/BZOJ4824 HEOI2013SAO/CQOI2017老C的键盘(树形dp)
    BZOJ4820 SDOI2017硬币游戏(概率期望+高斯消元+kmp)
    BZOJ4811 Ynoi2017由乃的OJ(树链剖分+线段树)
    BZOJ4810 Ynoi2017由乃的玉米田(莫队+bitset)
    Codeforces Round #522 Div. 1 没打记
    BZOJ4784 ZJOI2017仙人掌(树形dp+dfs树)
    43. Multiply Strings
    2. Add Two Numbers
    150. Evaluate Reverse Polish Notation
  • 原文地址:https://www.cnblogs.com/lmfeng/p/2621056.html
Copyright © 2011-2022 走看看