多线程锁机制的使用

示例代码:

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Incorrect Counter");
            Counter c1 = new Counter();
            var t1 = new Thread(() => TestCounter(c1));     //派生类等与实例化后的基类,c1 is CounterBase
            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("Total Count:{0}", c1.Count);
            Console.WriteLine("------------------------");

            Console.WriteLine("Correct counter");
            CounterWithLock c2 = new CounterWithLock();
            t1 = new Thread(() => TestCounter(c2));         //派生类等与实例化后的基类,c2 is CounterBase
            t2 = new Thread(() => TestCounter(c2));
            t3 = new Thread(() => TestCounter(c2));
            t1.Start();
            t2.Start();
            t3.Start();
            t1.Join();
            t2.Join();
            t3.Join();
            Console.WriteLine("Total Count:{0}", c2.Count);
        }

        static void TestCounter(CounterBase c)
        {
            for(int i=0;i<10000;i++)
            {
                c.Increment();      //增量
                c.Decrement();      //减量    
            }
        }

        class Counter : CounterBase        
        {
            public int Count { get; private set; }          //计算后的结果
            public override void Decrement()        //对定义的抽象方法重写
            {
                Count--;
            }
            public override void Increment()
            {
                Count++;
            }
        }
        class CounterWithLock : CounterBase
        {
            private readonly object _asyncRoot = new object();
            public int Count { get; private set; }
            public override void Decrement()
            {
                lock (_asyncRoot)            //这里也可以把全局静态变量_asyncRoot改成this
                {
                    Count--;
                }
            }

            public override void Increment()
            {
                lock(_asyncRoot)
                {
                    Count++;
                }
            }
        }

        abstract class CounterBase
        {
            public abstract void Increment();   //增量函数
            public abstract void Decrement();   //减量函数
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值