示例过于简单,不做过多解释

示例1

  1. package tool;
  2. import java.util.concurrent.CyclicBarrier;
  3. /**
  4. * {@link java.util.concurrent.CyclicBarrier}
  5. *
  6. * @author lihongjian
  7. * @since 2021/2/27
  8. */
  9. public class CyclicBarrierDemo {
  10. public static void main(String[] args) {
  11. Runnable barrierAction;
  12. CyclicBarrier cyclicBarrier = new CyclicBarrier(5, () -> {
  13. System.out.println("回调==>" + Thread.currentThread().getName());
  14. System.out.println("回调==>线程组执行结束");
  15. System.out.println("各个子线程执行结束");
  16. });
  17. for(int i = 0 ; i < 5 ; i++){
  18. new Thread(new Thread1(cyclicBarrier , i)).start();
  19. }
  20. }
  21. static class Thread1 implements Runnable{
  22. CyclicBarrier cyclicBarrier ;
  23. int id ;
  24. public Thread1(CyclicBarrier cyclicBarrier, int id) {
  25. this.cyclicBarrier = cyclicBarrier;
  26. this.id = id;
  27. }
  28. @Override
  29. public void run() {
  30. System.out.println("id:" + id + " "+ Thread.currentThread().getName());
  31. try {
  32. cyclicBarrier.await();
  33. System.out.println("线程组任务" + id + "执行结束,其他任务继续");
  34. } catch (Exception e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. }
  39. }

示例2

package tool;

import java.util.concurrent.CyclicBarrier;

/**
 * @author lihongjian
 * @since 2021/2/27
 */
public class CyclicBarrierDemo2 {
    public static void main(String[] args) throws InterruptedException {
        int N = 4;
        CyclicBarrier cyclicBarrier = new CyclicBarrier(N);

        for(int i = 0 ; i < N ; i++) {
            new Thread(new Writer(cyclicBarrier)).start();
        }
        Thread.sleep(10000);
        System.out.println("=======>CyclicBarrier复用");

        for(int i = 0 ; i < N ; i++) {
            new Thread(new Writer(cyclicBarrier)).start();
        }


    }

    static class Writer implements Runnable{
        CyclicBarrier cyclicBarrier ;

        public Writer(CyclicBarrier cyclicBarrier) {
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {

            System.out.println("线程" + Thread.currentThread().getName() + "正在写入数据");

            try {
                Thread.sleep(1000);//使用睡眠模拟业务逻辑
                cyclicBarrier.await();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " 所有线程写入完毕");
        }
    }
}