C# 多线程 顺序打印
时间: 2023-11-01 17:59:31 浏览: 149
C#多线程顺序打印可以使用AutoResetEvent线程排序打印的方法。可以参考以下示例代码:
```csharp
using System;
using System.Threading;
public class Printer
{
private AutoResetEvent[] syncEvents;
private int currentThreadIndex;
public Printer(int numThreads)
{
syncEvents = new AutoResetEvent[numThreads];
for (int i = 0; i < numThreads; i++)
{
syncEvents[i] = new AutoResetEvent(i == 0); }
}
public void PrintNumber(int number, int threadIndex)
{
syncEvents[threadIndex].WaitOne();
Console.WriteLine($"线程[{Thread.CurrentThread.Name}]打印数字:{number}");
Thread.Sleep(1000);
syncEvents[(threadIndex + 1) % syncEvents.Length].Set();
}
}
public class Program
{
public static void Main(string[] args)
{
int numThreads = 3;
Printer printer = new Printer(numThreads);
for (int i = 0; i < numThreads; i++)
{
int threadIndex = i; Thread thread = new Thread(() =>
{
for (int j = 0; j < 10; j++)
{
printer.PrintNumber(j, threadIndex);
}
});
thread.Name = $"Thread {i + 1}";
thread.Start();
}
Console.ReadLine();
}
}
```
该示例代码中,创建了一个Printer类来进行打印操作。使用AutoResetEvent数组来控制线程的顺序打印,每个线程都有一个对应的AutoResetEvent对象。在PrintNumber方法中,通过WaitOne方法等待上一个线程的AutoResetEvent对象信号,然后打印数字并休眠一段时间后释放下一个线程对应的AutoResetEvent对象。
阅读全文