Java concurrency: Countdown latch vs Cyclic barrier

前端 未结 14 2050
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 14:44

I was reading through the java.util.concurrent API, and found that

  • CountDownLatch: A synchronization aid that allows one or more threads to wait
14条回答
  •  执念已碎
    2020-11-29 15:16

    @Kevin Lee and @Jon I tried CyclicBarrier with Optional Runnable. Looks like it runs in the beginning and after the CyclicBarrier is tipped. Here is the code and output

    static CyclicBarrier barrier;

        public static void main(String[] args) throws InterruptedException {
            barrier = new CyclicBarrier(3, new Runnable() {
                @Override
                public void run() {
                    System.out.println("I run in the beginning and after the CyclicBarrier is tipped");
                }
            });
    
            new Worker().start();
            Thread.sleep(1000);
            new Worker().start();
            Thread.sleep(1000);
            new Worker().start();
            Thread.sleep(1000);
    
            System.out.println("Barrier automatically resets.");
    
            new Worker().start();
            Thread.sleep(1000);
            new Worker().start();
            Thread.sleep(1000);
            new Worker().start();
        }
    

    Output

    I run in the beginning and after the CyclicBarrier is tipped
    Let's play.
    Let's play.
    Let's play.
    Barrier automatically resets.
    I run in the beginning and after the CyclicBarrier is tipped
    Let's play.
    Let's play.
    Let's play.
    

提交回复
热议问题