CountDownLatch vs. Semaphore

后端 未结 6 1147
不知归路
不知归路 2020-11-28 01:30

Is there any advantage of using

java.util.concurrent.CountdownLatch

instead of

java.util.concurrent.Semaphore?

As far as I can tell the fol

6条回答
  •  孤独总比滥情好
    2020-11-28 01:53

    CountDownLatch is frequently used for the exact opposite of your example. Generally, you would have many threads blocking on await() that would all start simultaneously when the countown reached zero.

    final CountDownLatch countdown = new CountDownLatch(1);
    
    for (int i = 0; i < 10; ++ i) {
       Thread racecar = new Thread() {    
          public void run() {
             countdown.await(); //all threads waiting
             System.out.println("Vroom!");
          }
       };
       racecar.start();
    }
    System.out.println("Go");
    countdown.countDown();   //all threads start now!
    

    You could also use this as an MPI-style "barrier" that causes all threads to wait for other threads to catch up to a certain point before proceeding.

    final CountDownLatch countdown = new CountDownLatch(num_thread);
    
    for (int i = 0; i < num_thread; ++ i) {
       Thread t= new Thread() {    
          public void run() {
             doSomething();
             countdown.countDown();
             System.out.printf("Waiting on %d other threads.",countdown.getCount());
             countdown.await();     //waits until everyone reaches this point
             finish();
          }
       };
       t.start();
    }
    

    That all said, the CountDownLatch can safely be used in the manner you've shown in your example.

提交回复
热议问题