예제 #1
0
        static void Main(string[] args)
        {
            SingeltonDemo s1 = SingeltonDemo.GetInstance();
            SingeltonDemo s2 = SingeltonDemo.GetInstance();

            if (s1 == s2)
            {
                Console.WriteLine("equal");
            }
            object obj1    = null;
            object obj2    = null;
            Thread thread1 = new Thread(() =>
            {
                obj1 = SingeltonDemo.GetInstance1();
            });

            thread1.Start();
            Thread thread2 = new Thread(() =>
            {
                obj2 = SingeltonDemo.GetInstance1();
            });

            thread2.Start();
            thread1.Join();
            thread2.Join();
            if (obj2 != null && obj1 != null && obj2 == obj1)
            {
                Console.WriteLine("equal2");
            }
            Console.Read();
        }
예제 #2
0
 //非多线程
 public static SingeltonDemo GetInstance()
 {
     if (singeltonDemo == null)
     {
         singeltonDemo = new SingeltonDemo();
     }
     return(singeltonDemo);
 }
예제 #3
0
 //考虑多线程,但每次都加锁,耗资源
 public static SingeltonDemo GetInstance1()
 {
     lock (sy)
     {
         if (singeltonDemo2 == null)
         {
             singeltonDemo2 = new SingeltonDemo();
         }
     }
     return(singeltonDemo2);
 }