Java concurrency: Countdown latch vs Cyclic barrier

前端 未结 14 2108
隐瞒了意图╮
隐瞒了意图╮ 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:22

    This question has been adequately answered already, but I think I can value-add a little by posting some code.

    To illustrate the behaviour of cyclic barrier, I have made some sample code. As soon as the barrier is tipped, it is automatically reset so that it can be used again (hence it is "cyclic"). When you run the program, observe that the print outs "Let's play" are triggered only after the barrier is tipped.

    import java.util.concurrent.BrokenBarrierException;
    import java.util.concurrent.CyclicBarrier;
    
    public class CyclicBarrierCycles {
    
        static CyclicBarrier barrier;
    
        public static void main(String[] args) throws InterruptedException {
            barrier = new CyclicBarrier(3); 
    
            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();
        }
    
    }
    
    
    class Worker extends Thread {
        @Override
        public void run() {
            try {
                CyclicBarrierCycles.barrier.await();
                System.out.println("Let's play.");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
    

提交回复
热议问题