3、多线程-两个线程交替打印 0~100 的奇偶数
题目
两个线程交替打印 0~100 的奇偶数
代码示例
using System;
using System.Threading;
using System.Threading.Tasks;
public class ZeroEvenOdd
{
private int n = 100;
private AutoResetEvent evenEvent = new AutoResetEvent(false);
private AutoResetEvent oddEvent = new AutoResetEvent(true);
public void PrintEven(Action<int> printNumber)
{
for (int i = 0; i <= n; i += 2)
{
evenEvent.WaitOne(); // 等待 even 事件
printNumber(i); // 打印偶数
oddEvent.Set(); // 唤醒 odd 线程
}
}
public void PrintOdd(Action<int> printNumber)
{
for (int i = 1; i <= n; i += 2)
{
oddEvent.WaitOne(); // 等待 odd 事件
printNumber(i); // 打印奇数
evenEvent.Set(); // 唤醒 even 线程
}
}
public static void Main(string[] args)
{
ZeroEvenOdd zeroEvenOdd = new ZeroEvenOdd();
var evenTask = Task.Run(() => zeroEvenOdd.PrintEven(Console.Write));
var oddTask = Task.Run(() => zeroEvenOdd.PrintOdd(Console.Write));
Task.WaitAll(evenTask, oddTask);
Console.WriteLine();
}
}