netcore 俩个线程乱序调整

 

 

 class Program
    {
        public static long flgVal = 0;

        static void Main(string[] args)
        {
            int n = 100;
            Task.Run(() => DaMi(n));
            Task.Run(() => LaoShu(n));

            Console.Read();
        }

        public async static Task LaoShu(int n)
        {

            for (int i = 0; i < n; i++)
            {
                while (true)
                {

                    if (Interlocked.Read(ref flgVal) == 0)
                    {
                        break;
                    }
                }
                Console.Write("老鼠");
                Interlocked.Increment(ref flgVal);
            }
        }

        public async static Task DaMi(int n)
        {

            for (int i = 0; i < n; i++)
            {
                while (true)
                {

                    if (Interlocked.Read(ref flgVal) == 1)
                    {
                        break;
                    }
                }

                Console.Write("爱大米  ");
                Interlocked.Decrement(ref flgVal);


            }
        }







    }

 

posted @ 2021-06-15 12:26  沐雪架构师  阅读(61)  评论(0编辑  收藏  举报