Multi-threaded tool--CyclicBarrier

Write two examples of CyclicBarrier and Phaser.

One, CyclicBarrier. Thread reaches a certain number and executes together

public class Test_Cyclic {

    public static void main(String[] args) {


        CyclicBarrier cyclicBarrier = new CyclicBarrier(3, () -> System.out.println("执行"));

        for (int i = 0; i < 6; i++) {

            final int temp = i;
            new Thread(){

                @Override
                public void run() {
                    super.run();
                    System.out.println("线程" +temp + ":开始");
                    try {
                        cyclicBarrier.await();
                        System.out.println("线程" +temp + ":结束");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    }
}

result:

Guess you like

Origin blog.csdn.net/MrBack/article/details/114994685