java 多线程-CyclicBarrier(栅栏)

模拟的是一个游戏玩家匹配的过程

public static void main(String[] args) throws InterruptedException {
        int count = 10;
        List<Future<Integer>> futures = new ArrayList<>();
        ExecutorService executorService = Executors.newFixedThreadPool(count);
        CyclicBarrier cyclicBarrier = new CyclicBarrier(count,()->{
            System.out.println(futures.size() +":名玩家匹配完成");
        });
        for (int i = 0; i < count; i++) {
            Future<Integer> future = executorService.submit(() -> {

                try {
                    int seconds = 1 + (new Random().nextInt(4));
                    TimeUnit.SECONDS.sleep(seconds);
                    System.out.println(Thread.currentThread().getName() + ":游戏房间已匹配,等待其他玩家加入... ,匹配耗时:"+seconds);
                    cyclicBarrier.await();
                    System.out.println(Thread.currentThread().getName() + ":进入游戏");
                    return seconds;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            });
            futures.add(future);
        }
        executorService.shutdown();
        Integer avgLoading = 0;
        for (Future<Integer> future : futures) {
            try {
                avgLoading += future.get();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("平均加载耗时:" + (double)avgLoading / futures.size());
    }

执行结果

在这里插入图片描述

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值