zoukankan      html  css  js  c++  java
  • Phaser也可以实现countdownLatch的功能

    /**
     * 可用用phaser模拟countDownLatch
     * awaitAdvance方法:如果传入的参数和当前的phase相等,线程就阻塞住等待phase的值增加;否则就立即返回
     */
    public class PhaserTest2 {
    
        private static Random random = new Random(System.currentTimeMillis());
    
        public static void main(String[] args) throws InterruptedException {
            Phaser phaser = new Phaser(4);
            for (int i = 1; i <= 4; i++) {
                new AwaitAdvanceTask(i, phaser).start();
            }
            System.out.println("before: "+phaser.getPhase());
            int result = phaser.awaitAdvance(phaser.getPhase());
            System.out.println("after: "+phaser.getPhase());
            System.out.println("i = "+result);
        }
    
    
        static class AwaitAdvanceTask extends Thread {
    
    
            private int no;
            private Phaser phaser;
    
            AwaitAdvanceTask(int no, Phaser phaser) {
                this.no = no;
                this.phaser = phaser;
            }
    
            @Override
            public void run() {
                try {
                    Thread.sleep(random.nextInt(5000));
                    System.out.println(no + " has worked done");
                    phaser.arriveAndAwaitAdvance();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
  • 相关阅读:
    Lucene搜索引擎例子demo
    java Log4j日志配置详解大全
    java获取当前上一周、上一月、上一年的时间
    Django组件-cookie与session
    前端基础之jQuery
    Django组件-forms
    Django组件-分页器
    Django-Ajax
    Django模型层-多表操作
    Django模型层-单表操作
  • 原文地址:https://www.cnblogs.com/moris5013/p/11893309.html
Copyright © 2011-2022 走看看