想要同步3个线程,3个线程执行SignalAndWait()后等待,3个线程全部执行完,再都去各自执行剩下的。

static readonly Barrier barrier = new(3, it =>
{
  Console.WriteLine("再次集结,重新开跑");
});

static void Main(string[] args)
{
  string[] names = { "A", "B", "C" };
  foreach (string name in names)
  {
    new Thread(() => Run(name)).Start();
  }
  Console.ReadKey();
}

static void Run(string name)
{
  Console.WriteLine($"{name} running");
  int t = new Random().Next(1, 10);
  Thread.Sleep(t * 1000);
  Console.WriteLine($"{name}用时{t}秒,跑到集结点");
  barrier.SignalAndWait();
  Console.WriteLine($"{name}重新开始跑");
}