1.CyclicBarrier loop fence
principle
CyclicBarrier literally means a cyclic (Cyclic) barrier (Barrier). What it has to do is to block a group of threads when they reach a barrier (also called a synchronization point). The barrier will not open until the last thread reaches the barrier, and all threads intercepted by the barrier will continue to work. The thread enters the barrier through the await() method of CyclicBarrier.
code
package com.atguigu.thread;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
/**
*
* @Description: TODO (here one sentence describes the role of this class)
* @author xialei
*
* CyclicBarrier
* Literally means a barrier that can be used by Cyclic. What it has to do is,
* Let a group of threads be blocked when they reach a barrier (also called a synchronization point),
* The barrier will not open until the last thread reaches the barrier, all
* The thread intercepted by the barrier will continue to work.
* The thread enters the barrier through the await() method of CyclicBarrier.
*
* Collect 7 dragon balls to summon the dragon
*/
public class CyclicBarrierDemo
{
private static final int NUMBER = 7;
public static void main(String[] args)
{
//CyclicBarrier(int parties, Runnable barrierAction)
CyclicBarrier cyclicBarrier = new CyclicBarrier(NUMBER, ()->{System.out.println("*****Gather 7 dragon balls to summon the dragon");});
for (int i = 1; i <= 7; i++) {
new Thread(() -> {
try {
System.out.println(Thread.currentThread().getName()+"\t Star Dragon Ball is collected");
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
}
}, String.valueOf(i)).start();
}
}
}