In-depth understanding of JUC: Chapter V: CyclicBarrier cycle fence

theory:

Its role is to make all threads continue to wait until after the completion of the next move.

For example, we'll just go about life friends to a restaurant for dinner, some people may be early, some people may be a little late, but the restaurant provision must wait until after everyone in attendance let us . Here is the various threads of my friends, the restaurant is CyclicBarrier.

Unused code fence cycle:

public class Demo {

    public static void main(String[] args) throws Exception{
        for (int i = 1; i <= 6; i++) {
            final int tempInt = i;
            new Thread(()->{
                System.out.println(tempInt+"朋友到了");
            },String.valueOf(i)).start();
        }
        System.out.println("朋友全部到了,才开始吃饭");
    }
}

Console:

Use CyclicBarrier code:

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;


public class Demo {

    public static void main(String[] args) throws Exception{
        CyclicBarrier cyclicBarrier = new CyclicBarrier(6,()->{System.out.println("朋友全部到了,才开始吃饭");});
        for (int i = 1; i <= 6; i++) {
            final int tempInt = i;
            new Thread(()->{
                System.out.println(tempInt+"朋友到了");
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            },String.valueOf(i)).start();

        }
    }
}

Console:

 

 

 

 

Published 276 original articles · won praise 181 · views 50000 +

Guess you like

Origin blog.csdn.net/java_wxid/article/details/99171155