Exemplo n.º 1
0
        private static void MultiThreadingEx()
        {
            Thread t1 = new Thread(
                new ThreadStart(() =>
            {
                for (int i = 0; i < 3; i++)
                {
                    SingletonA.GetInstance();
                    Console.WriteLine("H1: " + SingletonA.Mensaje);
                    //Thread.Sleep(1000);
                    var instanciasinglemth1 = SingletonLazy.Instance;
                    //Console.WriteLine("H1: " + SingletonLazy.Mensaje);
                    //Thread.Sleep(1000);
                }
            }));

            Thread t2 = new Thread(
                new ThreadStart(() =>
            {
                for (int i = 0; i < 3; i++)
                {
                    SingletonA.GetInstance();
                    Console.WriteLine("H2: " + SingletonA.Mensaje);
                    //Thread.Sleep(1000);
                    var instanciasinglemth1 = SingletonLazy.Instance;
                    //Console.WriteLine("H2: " + SingletonLazy.Mensaje);
                    // Thread.Sleep(1000);
                }
            }));

            t1.Start();
            t2.Start();
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            //三次打印相同的hashcode 使用的同一个实例
            for (int i = 0; i < 3; i++)
            {
                //饿汉
                SingletonA singletonA = SingletonA.GetInstance();
                singletonA.PrintMsg();
            }

            //三次打印相同的hashcode 使用的同一个实例
            for (int i = 0; i < 3; i++)
            {
                //懒汉
                SingletonB singletonB = SingletonB.GetInstance();
                singletonB.PrintMsg();
            }

            Console.ReadKey();
        }