CyclicBarrier

Multiple threads wait for each other on a barrier until all threads have arrived, and then a synchronization program is executed

Example: 1000W orders need to be processed, divided into 1000 batches

import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; public class CyclicBarrierTest { CyclicBarrier barrier; /** * int page = 0; Public CyclicBarrierTest() {CyclicBarrier = new CyclicBarrier(2, () -> {system.out.println ("Sync"); CyclicBarrier = new CyclicBarrier(2, () -> {system.out.println ("Sync"); page++; try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); }}); } void prepareProducts() {while (page < 1000) {try {system.out.println ("fetch product... ); barrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); }}} void prepareYorders () {while (page < 1000) {try {system.out.println ("fetch delivery Orders... ); barrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } } } void run() { new Thread(this::prepareProducts).start(); new Thread(this::prepareDeliveryOrders).start(); } public static void main(String[] args) { var test = new CyclicBarrierTest(); test.run(); }}Copy the code