C#实现多线程交替打印数字

private static List<AutoResetEvent> autoResetEvents = new List<AutoResetEvent>();
private static int num = 0;
/// 
/// 
/// 
/// 任务数
/// 每个任务打印的数字个数
static void WriteNum(int taskCount,int numCount)
{
    for (int i = 0; i < taskCount; i++)
    {
        autoResetEvents.Add(new AutoResetEvent(false));

        int setEventIndex = i + 1;
        if (i == (taskCount - 1))
        {
            setEventIndex = 0;
        }

        int[] taskParams = { i, setEventIndex };
        Task task = Task.Factory.StartNew((obj) => {
            var set = (int[])obj;
            for (int j = 0; j < numCount; j++)
            {
                autoResetEvents[set[0]].WaitOne();
                num++;
                Console.WriteLine($"线程ID:{Task.CurrentId},值:{num}");
                autoResetEvents[set[1]].Set();

            }
        }, taskParams);
    }
    autoResetEvents[0].Set();
}

你可能感兴趣的:(C#)