using System; using System.Threading; class PrintThread { private string name; private int count; private int repeat; private AutoResetEvent waitEvent; private AutoResetEvent nextEvent; public PrintThread(string name, int count, int repeat, AutoResetEvent waitEvent, AutoResetEvent nextEvent) { this.name = name; this.count = count; this.repeat = repeat; this.waitEvent = waitEvent; this.nextEvent = nextEvent; } public void Run() { for (int i = 0; i < repeat; i++) { waitEvent.WaitOne(); // 等待前一个线程的信号 for (int j = 0; j < count; j++) { Console.WriteLine("{0}: {1}", name, j + 1); Thread.Sleep(100); } nextEvent.Set(); // 通知下一个线程继续执行 } } } class Program { static void Main(string[] args) { AutoResetEvent eventA = new AutoResetEvent(false); AutoResetEvent eventB = new AutoResetEvent(false); AutoResetEvent eventC = new AutoResetEvent(false); PrintThread threadA = new PrintThread("AA", 5, 10, eventC, eventA); PrintThread threadB = new PrintThread("BB", 10, 10, eventA, eventB); PrintThread threadC = new PrintThread("CC", 15, 10, eventB, eventC); Thread tA = new Thread(threadA.Run); Thread tB = new Thread(threadB.Run); Thread tC = new Thread(threadC.Run); tA.Start(); tB.Start(); tC.Start(); // 启动第一轮打印任务 eventC.Set(); // 等待所有线程完成打印任务 tA.Join(); tB.Join(); tC.Join(); Console.WriteLine("All threads have finished printing."); } }
在这段代码中,我们创建了三个PrintThread
对象,分别表示线程 AA、BB 和 CC。每个线程负责打印一定数量的数字,并在打印完成之后等待下一个线程的信号。我们使用AutoResetEvent
来实现线程之间的信号传递。
在主程序中,我们创建了三个AutoResetEvent
对象,并将它们分别传递给线程 CC、AA 和 BB。然后,我们启动这三个线程,并使用第一个AutoResetEvent
对象启动第一轮打印任务。在每轮打印任务结束之后,我们使用下一个AutoResetEvent
对象通知下一个线程继续执行。最终,我们等待所有线程完成打印任务,并输出一条完成消息。