zoukankan      html  css  js  c++  java
  • C# InterLock保证数据一致性

        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();
            }
        }
  • 相关阅读:
    JAVA内部类详解
    表、栈和队列
    大型网站架构演化<二>
    eclipse中build path 中JDK与java compiler compliance level的问题(转)
    XFire构建服务端Service的两种方式
    SpringMVC简单例子
    Mybatis
    java静态代码块 类加载顺序问题。
    Tomcat6.0数据源配置
    解析xml的几种方式
  • 原文地址:https://www.cnblogs.com/shidengyun/p/5599702.html
Copyright © 2011-2022 走看看