class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Increment counter");
            var c = new Counter();
            var t1 = new Thread(() => TestCounter(c));
            var t2 = new Thread(() => TestCounter(c));
            var 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("end Increment");

            var c1 = new CounterNoLock();

            t1 = new Thread(() => TestCounter(c));
            t2 = new Thread(() => TestCounter(c));
            t3 = new Thread(() => TestCounter(c));

            t1.Start();
            t2.Start();
            t3.Start();
            t1.Join();
            t2.Join();
            t3.Join();
            Console.WriteLine("Total Count:{0}", c1.Count);
            Console.WriteLine("end CounterNoLock");

        }
        static void TestCounter(CounterBase c)
        {
            for (int i = 0; i < 10000; i++)
            {
                c.Increment();
                c.Decrement();
            }
        }
        class Counter : CounterBase
        {
            private int _count;
            public int Count { get { return _count; } }
            public override void Increment()
            {
                _count++;
            }
            public override void Decrement()
            {
                _count--;
            }
        }
        class CounterNoLock : CounterBase
        {
            private int _count;
            public int Count { get { return _count; } }
            public override void Increment()
            {
                Interlocked.Increment(ref _count);
            }
            public override void Decrement()
            {
                Interlocked.Decrement(ref _count);
            }
        }
        abstract class CounterBase
        {
            public abstract void Increment();
            public abstract void Decrement();
        }
    }

相关文章:

  • 2021-04-01
  • 2021-11-21
  • 2022-12-23
  • 2021-08-30
  • 2021-11-20
猜你喜欢
  • 2021-11-28
  • 2022-12-23
  • 2021-12-11
  • 2022-01-02
  • 2019-08-11
  • 2021-07-16
  • 2022-01-18
相关资源
相似解决方案