java 多线程-CyclicBarrier(栅栏)

2023-12-15 16:41:21

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

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());
    }

执行结果

在这里插入图片描述

文章来源:https://blog.csdn.net/L630642270/article/details/135016658
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。