• java CyclicBarrier


    import java.io.IOException;
    import java.util.Random;
    import java.util.concurrent.BrokenBarrierException;
    import java.util.concurrent.CyclicBarrier;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
     public class R {  
      
        public static void main(String[] args) throws IOException, InterruptedException {  
            //如果将参数改为4,但是下面只加入了3个选手,这永远等待下去  
            //Waits until all parties have invoked await on this barrier.   
            CyclicBarrier barrier = new CyclicBarrier(3);  
      
            ExecutorService executor = Executors.newFixedThreadPool(3);  
            executor.submit(new Thread(new Runner(barrier, "1号选手")));  
            executor.submit(new Thread(new Runner(barrier, "2号选手")));  
            executor.submit(new Thread(new Runner(barrier, "3号选手")));  
      
            executor.shutdown();  
        }  
    }  
      
    class Runner implements Runnable {  
        // 一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point)  
        private CyclicBarrier barrier;  
      
        private String name;  
      
        public Runner(CyclicBarrier barrier, String name) {  
            super();  
            this.barrier = barrier;  
            this.name = name;  
        }  
      
        @Override  
        public void run() {  
            try {  
                Thread.sleep(1000 * (new Random()).nextInt(8));  
                System.out.println(name + " 准备好了...");  //
                // barrier的await方法,在所有参与者都已经在此 barrier 上调用 await 方法之前,将一直等待。  
                //barrier.await();  关闭此处,所有线程各自执行会不影响
                
                //让barrier中所有线程 做完 barrier.await()之前的任务,
                //比如 "System.out.println(name + " 准备好了..."); "   然后才继续下面的任务
                barrier.await(); 
               
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            } catch (BrokenBarrierException e) {  
                e.printStackTrace();  
             }  
            System.out.println(name + " 起跑!");  
        }  
    } 
  • 相关阅读:
    如何设置QT的窗口图标和exe应用程序图标(两步搞定操作)
    怎么打包发布QT程序(图文详解)
    QT实现读取sps文件并将数据显示在TableView中(复习)
    LeetCode第一题——两数之和
    大型数据库复习
    Android复习
    C#桌面程序设计复习
    WordCount扩展与优化
    第二次作业(WordCount)重制版
    第二次作业(WordCount)
  • 原文地址:https://www.cnblogs.com/rojas/p/5367297.html
Copyright © 2020-2023  润新知