C#多线程同步(一)【计数器】

罗马人凯撒大帝,威震欧亚非三大陆,临终告诉侍者说:“请把我的双手放在棺材外面,让世人看看,伟大如我凯撒者,死后也是两手空空。


ICounter.cs类:

interface ICounter
    {
        void Increment();
        void Decrement();
    }

Counter.cs类:

 class Counter : ICounter
    {
        private int _count = 0;
        public int Count { get { return _count; } }
        public void Increment()
        {
            _count ++;
        }

        public void Decrement()
        {
            _count--;
        }
    }

CounterLock.cs代码:

 class CounterLock : ICounter
    {
        private int _count;

        public int Count { get { return _count; } }
        public void Increment()
        {
            Interlocked.Increment(ref _count);
        }

        public void Decrement()
        {
            Interlocked.Decrement(ref _count);
        }
    }

Test.cs代码:

 class Test
    {
        public static void TestCounter(ICounter c)
        {
            for (int i = 0; i < 100000; i ++)
            {
                c.Increment();
                c.Decrement();
            }
        }

        public static void RunTest()
        {
            var c1 = new Counter();
            var t1 = new Thread((() => TestCounter(c1)));
            var t2 = new Thread((() => TestCounter(c1)));
            var t3 = new Thread((() => TestCounter(c1)));
            t1.Start();
            t2.Start();
            t3.Start();
            t1.Join();
            t2.Join();
            t3.Join();

            Console.WriteLine("总数: {0}", c1.Count);
            Console.WriteLine("--------------------------");
            Console.WriteLine("普通计数器");
            Console.WriteLine("");
            var c2 = new CounterLock();
            t1 = new Thread((() => TestCounter(c2)));
            t2 = new Thread((() => TestCounter(c2)));
            t3 = new Thread((() => TestCounter(c2)));
            t1.Start();
            t2.Start();
            t3.Start();
            t1.Join();
            t2.Join();
            t3.Join();

            Console.WriteLine("总数: {0}", c2.Count);
            Console.WriteLine("--------------------------");
            Console.WriteLine("线程同步的计数器");

            Console.ReadKey();
        }
    }

运行结果如图:

这里写图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值