【进程线程与同步】5.4 System.Threading.Interlocked 为多个线程共享的变量提供原子操作

    using System;
    using System.Threading;
    internal class Program
    {
        private static long _counter = 1;

        private static void Main()
        {
            //下面程序显示两个线程如何并发访问一个名为counter的整形变量,一个线程让他递增5次,一个让他递减5次
            Console.WriteLine("原始值:{0}", _counter);
            var t1 = new Thread(F1);
            var t2 = new Thread(F2);
            t1.Start();
            t2.Start();
            t1.Join();
            t2.Join();
            Console.WriteLine("最终值:{0}", _counter);
            Console.Read();
        }

        private static void F1()
        {
            for (int i = 0; i < 5; i++)
            {
                Interlocked.Increment(ref _counter);//原子性操作
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ff") + " 方法1:counter++:{0}", _counter);
                Thread.Sleep(10);
            }
        }

        private static void F2()
        {
            for (int i = 0; i < 5; i++)
            {
                Interlocked.Decrement(ref _counter);//原子性操作
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ff") + " 方法2:counter--:{0}", _counter);
                Thread.Sleep(10);
            }
        }
    }

上一篇:关于dns使用协议的探究


下一篇:zigbee协议栈学习(五)