Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            {
                //单线程-非单例
                for (int i = 0; i < 10; i++)
                {
                    Func func = new Func();
                    func.Show();
                }

                //单线程-单例
                for (int i = 0; i < 10; i++)
                {
                    SingleFunc single = SingleFunc.CreateObject();
                    single.Show();
                }
            }

            {
                //多线程-单例
                for (int i = 0; i < 10; i++)
                {
                    new Action(() =>
                    {
                        SingleFunc single = SingleFunc.CreateObject();
                        single.Show();
                    }).BeginInvoke(null, null);
                }
            }

            Console.ReadKey();
        }
Ejemplo n.º 2
0
 public static SingleFunc CreateObject()
 {
     if (single == null)//防止多线程等待锁
     {
         lock (lockObj)
         {
             //假如此时有耗时功能,最外层判断可以防止多线程等锁
             //Thread.Sleep(1000);
             if (single == null)
             {
                 single = new SingleFunc();
             }
         }
     }
     return(single);
 }