• 多线程编程(9)Barrier


    魔兽世界组队下副本

    下副本一般都要找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");
        }
    }

    结果

    image

  • 相关阅读:
    BZOJ 1150 [CTSC2007]数据备份Backup(贪心+优先队列)
    BZOJ 1053 [HAOI2007]反素数ant(约数个数)
    BZOJ 1066 [SCOI2007]蜥蜴(最大流)
    CodeForces 772A Voltage Keepsake
    HDU 6030 Happy Necklace
    HDU 6031 Innumerable Ancestors
    HDU 6026 Deleting Edges
    HDU 6024 Building Shops
    HDU 6029 Graph Theory
    HDU 6025 Coprime Sequence
  • 原文地址:https://www.cnblogs.com/Clingingboy/p/1881593.html
Copyright © 2020-2023  润新知