• 多线程06-Lock


        class Program
        {
            static void Main()
            {
                Console.WriteLine("Start");
                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();
                Console.WriteLine("Total:{0}", c.Count);
                var d = new CounterWithLock();
                var d1 = new Thread(() => TestCounter(d));
                var d2 = new Thread(() => TestCounter(d));
                var d3 = new Thread(() => TestCounter(d));
                d1.Start();
                d2.Start();
                d3.Start();
                Console.WriteLine("Total:{0}", d.Count);
                //Console.ReadKey();
            }
            static void TestCounter(CounterBase c)
            {
                for (var i = 0; i < 10000000; i++)
                {
                    c.Increment();
                    c.Decrement();
                }
            }
            class Counter : CounterBase
            {
                private int _counter;
                public int Count { get { return _counter; } }
                public override void Increment()
                {
                    _counter++;
                }
                public override void Decrement()
                {
                    _counter--;
                }
            }
            class CounterWithLock : CounterBase
            {
                private int _counter;
                public int Count { get { return _counter; } }
                public readonly object _synvRoot = new object();
                public override void Increment()
                {
                    lock (_synvRoot)
                    {
                        _counter++;
                    }
                }
                public override void Decrement()
                {
                    lock (_synvRoot)
                    {
                        _counter--;
                    }
                }
            }
            abstract class CounterBase
            {
                public abstract void Increment();
                public abstract void Decrement();

            }
        }
  • 相关阅读:
    linux下安装mysql
    python -- 相对路径、绝对路径、以及路径的获取
    Jekyll 使用入门
    argparse 使用指南
    requests快速入门
    Pandoc中的Markdown语法
    利用Github Pages建立仓库“门面”
    Anaconda使用入门
    Python连接SQL Server数据库
    SQL Server 部署CLR程序集错误`6218`
  • 原文地址:https://www.cnblogs.com/shidengyun/p/5600799.html
Copyright © 2020-2023  润新知