CountDownLatch and CyclicBarrier learning

Both CountDownLatch and CyclicBarrier have a counter

CountDownLatch countDownLatch = new CountDownLatch(4);
CyclicBarrier cyclicBarrier = new CyclicBarrier(4)

CountDownLatch is 4-1 after countDownLatch.countDown() is executed. After 4 is reduced to 0, you can continue to execute the program, otherwise it will keep waiting.

CyclicBarrier is also 4-1 after the execution of cyclicBarrier.await(). After 4 is reduced to 0, you can continue to execute the program, otherwise it will always wait.

What's the difference between the two? for example

There are 4 people in the office

CountDownLatch is for the four of you to finish the work. When you all finish the work, let me say a few words.

Cyclic Barrier is for the four of you to finish your work. When everyone is finished, you can continue to work.

The lock CountDownLatch is used to wait for events, and the barrier CyclicBarrier is used to wait for other threads.

CountDownLatch means that after all four threads have executed countDown, the program continues to run downward. The following things have nothing to do with the four threads, but have to do with the CountDownLatch.await() method, which waits for the four of you to finish the work. It's similar to DIYing your own computer here. You buy the host, CPU, power supply, motherboard, etc., and you have to wait for all the couriers to arrive before you can install the computer.

CyclicBarrier means that all four threads start awaiting after executing a certain step, and continue working after all waiting people arrive. This is similar to King of Glory. After 10 people enter the loading page, they must wait until all 10 people are loaded before they can enter the game interface.

Come demo

    @Test
    public void testCount() throws InterruptedException {
        ArrayList<String> list = Lists.newArrayList("cpu", "显示器", "主板", "电源", "机箱", "鼠标", "键盘");
        int size = list.size();
        ExecutorService executorService = Executors.newFixedThreadPool(size);
        //程序计数器
        CountDownLatch countDownLatch = new CountDownLatch(size);
        for (int i = 0; i < size; i++) {
            int finalI = i;
            executorService.submit(() -> {
                System.out.println("快递【"+list.get(finalI)+"】已送达");
                countDownLatch.countDown();
                long count = countDownLatch.getCount();
                System.out.println("快递总共有"+size+"个,目前还剩下"+count+"个未到达");
            });
            Thread.sleep(10);
        }
        Thread.sleep(1000);
        countDownLatch.await();
        System.out.println("快递已经到达完毕,开始组装玩游戏");
        //线程池 等待10s
        executorService.awaitTermination(10, TimeUnit.SECONDS);
        //关闭线程 其实是将线程状态设置为中断标志  必须等待所有线程处理完任务,才能完全关闭
        executorService.shutdown();
    }

 

    @Test
    public void testCyclicBarrier() throws InterruptedException {
        ArrayList<String> list = Lists.newArrayList("user1", "user2", "user3", "user4", "user5", "user6", "user7", "user8", "user9", "user10");
        int size = list.size();
        ExecutorService executorService = Executors.newFixedThreadPool(size);
        CyclicBarrier cyclicBarrier = new CyclicBarrier(size, () -> {
            System.out.println("所有人加载完毕,欢迎进入游戏!");
        });
        for (int i = 0; i < list.size(); i++) {
            int finalI = i;
            executorService.submit(
                    new Thread(() -> {
                        try {
                            System.out.println("用户【" + list.get(finalI) + "】选完英雄,进入加载界面,等待其他人加载.....");
                            cyclicBarrier.await();  // 等待其他线程到齐,到齐了之后就会执行一次
                            System.out.println("用户【" + list.get(finalI) + "】加载游戏完成,进入游戏,开始游戏");
                        } catch( Exception e) {
                            e.printStackTrace();
                        }
                    }));
        }
        executorService.awaitTermination(10, TimeUnit.SECONDS);
        executorService.shutdown();
    }

Guess you like

Origin blog.csdn.net/cclovezbf/article/details/131943106