多線程交替輸出數字和字母

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        static string[] numStr = new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
        static string[] Str = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
        static readonly AutoResetEvent auto = new AutoResetEvent(false);
        static readonly AutoResetEvent auto2 = new AutoResetEvent(false);
        static void Main(string[] args)
        {
            new Task(() =>
            {
                foreach (var temp in numStr)
                {
                    Console.WriteLine(temp);
                    auto2.Set();
                    auto.WaitOne();
                }
    
            }).Start();

            new Task(() =>
            {
       
                foreach (var temp in Str)
                {
                    auto2.WaitOne();
                    Console.WriteLine(temp);
                    auto.Set();
                };
            }).Start();
            Console.ReadKey();
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章