魔兽世界组队下副本
下副本一般都要找5个人,一般玩家都在副本门口等,然后等待其他玩家跑过来
即玩家在做两个动作
1.跑到副本门口
2.等5个人到齐了,然后进副本.
如果玩家先到就得等其他玩家到了才可以下副本,即大家跑到副本门口的时间是不同的,但进副本的时间是相同的(保持线程同步).
示例代码如下
public class Demo6 { Barrier barrier=new Barrier(5); public Demo6() { ThreadPool.QueueUserWorkItem(new WaitCallback(Task1)); ThreadPool.QueueUserWorkItem(new WaitCallback(Task2)); ThreadPool.QueueUserWorkItem(new WaitCallback(Task3)); ThreadPool.QueueUserWorkItem(new WaitCallback(Task4)); ThreadPool.QueueUserWorkItem(new WaitCallback(Task5)); } public void Task1(object obj) { Thread.Sleep(1000); Console.WriteLine(DateTime.Now); Console.WriteLine("Task1"); barrier.SignalAndWait(); Console.WriteLine("Task1 DoConcurrent"); } public void Task2(object obj) { Thread.Sleep(2000); Console.WriteLine(DateTime.Now); Console.WriteLine("Task2"); barrier.SignalAndWait(); Console.WriteLine("Task2 DoConcurrent"); } public void Task3(object obj) { Thread.Sleep(3000); Console.WriteLine(DateTime.Now); Console.WriteLine("Task3"); barrier.SignalAndWait(); Console.WriteLine("Task3 DoConcurrent"); } public void Task4(object obj) { Thread.Sleep(4000); Console.WriteLine(DateTime.Now); Console.WriteLine("Task4"); barrier.SignalAndWait(); Console.WriteLine("Task4 DoConcurrent"); } public void Task5(object obj) { Thread.Sleep(5000); Console.WriteLine(DateTime.Now); Console.WriteLine("Task5"); barrier.SignalAndWait(); Console.WriteLine("Task5 DoConcurrent"); } }
结果