Lock关键字

 public abstract class CountBase
    {
        public abstract void Increment();
        public abstract void Decreament();
    }
View Code
 public class Counter:CountBase
    {
        public int Count
        {
            get;
            set;
        }
        public override void Increment()
        {
            Count++;
        }

        public override void Decreament()
        {
            Count--;
        }
    }
View Code
  public class CounterWithLock:CountBase
    {
        private readonly object o = new object(); 
        public int Count
        {
            get;
            set;
        }
        public override void Increment()
        {
            lock (o)
            {
                Count++;
            }
        }

        public override void Decreament()
        {
            lock (o)
            {
                Count--;
            }
        }
    }
View Code
 static void Main(string[] args)
        {
            Counter c = new Counter();
            Thread t1 = new Thread(() => TestCounter(c));
            Thread t2 = new Thread(() => TestCounter(c));
            Thread t3 = new Thread(() => TestCounter(c));
            t1.Start();
            t2.Start();
            t3.Start();
            t1.Join();
            t2.Join();
            t3.Join();
            Console.WriteLine("Total Count:{0}", c.Count);
            Console.WriteLine("------------------------");
            Console.WriteLine("Correct couter");

            CounterWithLock l = new CounterWithLock();

            Thread t4 = new Thread(() => TestCounter(l));
            Thread t5 = new Thread(() => TestCounter(l));
            Thread t6 = new Thread(() => TestCounter(l));
            t4.Start();
            t5.Start();
            t6.Start();
            t4.Join();
            t5.Join();
            t6.Join();
            Console.WriteLine("Total Count:{0}", l.Count);
            Console.WriteLine("------------------------");
            Console.WriteLine("Correct LocakCouter");


        }
原文地址:https://www.cnblogs.com/sportdog/p/9504640.html