java multithreading: circulation barrier

This article is a video https://www.bilibili.com/video/av81181427 notes

Circulation barrier

The previous , we talked about multi-thread counter. Here we are in terms of circulation barrier.
In fact, the cycle counter and the like barrier function, which can be seen as a combination of countdown counters and await method:

public static void main(String[] args) throws InterruptedException {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    Thread.sleep(new Double(Math.random() * 3000).longValue());
                    System.out.println(Thread.currentThread().getName() + "玩家准备就绪");
                    cyclicBarrier.await();
                    System.out.println(Thread.currentThread().getName() + "玩家选择英雄");
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

Its output is:

Thread-2玩家准备就绪
Thread-4玩家准备就绪
Thread-3玩家准备就绪
Thread-1玩家准备就绪
Thread-0玩家准备就绪
Thread-0玩家选择英雄
Thread-2玩家选择英雄
Thread-3玩家选择英雄
Thread-4玩家选择英雄
Thread-1玩家选择英雄

It can be seen that, when the number of previous cycles of the internal barrier reaches zero, all threads are blocked in the cyclicBarrier
as a combination of the method and its effects countdown of the following:

CountDownLatch countDownLatch=new CountDownLatch(5);
        for(int i=0;i<10;i++){
            new Thread(()->{
                try{
                    Thread.sleep(new Double(Math.random()*3000).longValue());
                    System.out.println(Thread.currentThread().getName()+"玩家准备就绪");
                    countDownLatch.countDown();//计数点
                    countDownLatch.await();
                    System.out.println(Thread.currentThread().getName()+"玩家选择英雄");
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }).start();
        }

As for why it is called "recycling" barrier, this is because the numbers within it is reduced to 0 after can be restored to the original, for example, if we remain parameter is 5, but to create a 10 threads:

Thread-4玩家准备就绪
Thread-5玩家准备就绪
Thread-2玩家准备就绪
Thread-1玩家准备就绪
Thread-3玩家准备就绪
Thread-3玩家选择英雄
Thread-4玩家选择英雄
Thread-5玩家选择英雄
Thread-2玩家选择英雄
Thread-1玩家选择英雄
Thread-0玩家准备就绪
Thread-6玩家准备就绪
Thread-7玩家准备就绪
Thread-8玩家准备就绪
Thread-9玩家准备就绪
Thread-9玩家选择英雄
Thread-0玩家选择英雄
Thread-6玩家选择英雄
Thread-7玩家选择英雄
Thread-8玩家选择英雄

Guess you like

Origin www.cnblogs.com/jiading/p/12368912.html
Recommended