Theory:

All it does is make all threads wait for completion before proceeding to the next step.

For example, in our daily life, we will invite friends to a restaurant for dinner. Some friends may arrive early and some may arrive late, but the restaurant rules will not let us in until everyone is present. The friends are the threads and the restaurant is the CyclicBarrier.

Code that does not use a loop fence:

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+" friend "); },String.valueOf(i)).start(); } system.out.println (" friends are all here, then start eating "); }}Copy the code

Console:

Code to use CyclicBarrier:

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 (" all friends are here "); CyclicBarrier(6,()->{system.out.println (" all friends are here "); }); for (int i = 1; i <= 6; i++) { final int tempInt = i; New Thread(()->{system.out.println (tempInt+" friend "); try { cyclicBarrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } },String.valueOf(i)).start(); }}}Copy the code

Console: