题目
用两个线程,一个输出字母,一个输出数字,交替输出 1A2B3C4D...26Z
代码示例
using System;
using System.Threading;
using System.Threading.Tasks;public class NumberLetterPrinter
{private AutoResetEvent numberEvent = new AutoResetEvent(true); // 一开始数字线程可以运行private AutoResetEvent letterEvent = new AutoResetEvent(false); // 字母线程一开始不能运行public void PrintNumber(Action<int> printNumber){for (int i = 1; i <= 26; i++){numberEvent.WaitOne(); // 等待数字事件printNumber(i); // 打印数字letterEvent.Set(); // 唤醒字母线程}}public void PrintLetter(Action<char> printLetter){for (int i = 0; i < 26; i++){letterEvent.WaitOne(); // 等待字母事件printLetter((char)('A' + i)); // 打印字母numberEvent.Set(); // 唤醒数字线程}}public static void Main(string[] args){NumberLetterPrinter printer = new NumberLetterPrinter();var numberTask = Task.Run(() => printer.PrintNumber(Console.Write));var letterTask = Task.Run(() => printer.PrintLetter(Console.Write));Task.WaitAll(numberTask, letterTask);Console.WriteLine();}
}