时间:2022-01-29 09:56:48 | 栏目:.NET代码 | 点击:次
可能的输出:
All jobs have been done.
代码:
class BarrierDemo
{
static Barrier _barrier = new Barrier (5, barrier => {
Console.WriteLine();
Console.WriteLine("All jobs have been done.");
});
static void Main()
{
Random r = new Random();
new Thread(Work).Start(new MyThreadArgs { ThreadId = "A",
WaitTimeCount = r.Next(1000) });
new Thread(Work).Start(new MyThreadArgs {ThreadId = "B",
WaitTimeCount = r.Next(1000) });
new Thread(Work).Start(new MyThreadArgs {ThreadId = "C",
WaitTimeCount = r.Next(1000) });
new Thread(Work).Start(new MyThreadArgs {ThreadId = "D",
WaitTimeCount = r.Next(1000) });
new Thread(Work).Start(new MyThreadArgs {ThreadId = "E",
WaitTimeCount = r.Next(1000) });
}
static void Work(object obj)
{
MyThreadArgs args = (MyThreadArgs) obj;
Console.WriteLine("Working on Thread " + args.ThreadId);
Console.WriteLine("Thread " + args.ThreadId +
" will sleep for " + args.WaitTimeCount + " seconds.");
Thread.Sleep(waitTime);
_barrier.SignalAndWait();
}
class MyThreadArgs
{
public string ThreadId { get; set; }
public int WaitTimeCount { get; set; }
}
}