CountDownLatch与Semaphore [英] CountDownLatch vs. Semaphore

查看:205
本文介绍了CountDownLatch与Semaphore的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用

java.util.concurrent.CountdownLatch

而不是

java.util.concurrent.Semaphore

据我所知,以下片段几乎是等效的:

As far as I can tell the following fragments are almost equivalent:

1。信号量

final Semaphore sem = new Semaphore(0);
for (int i = 0; i < num_threads; ++ i)
{
  Thread t = new Thread() {
    public void run()
    {
      try
      {
        doStuff();
      }
      finally
      {
        sem.release();
      }
    }
  };
  t.start();
}

sem.acquire(num_threads);

2:CountDownLatch

final CountDownLatch latch = new CountDownLatch(num_threads);
for (int i = 0; i < num_threads; ++ i)
{
  Thread t = new Thread() {
    public void run()
    {
      try
      {
        doStuff();
      }
      finally
      {
        latch.countDown();
      }
    }
  };
  t.start();
}

latch.await();

除了在#2情况下闩锁不能重复使用,更重要的是你需要提前知道如何

Except that in case #2 the latch cannot be reused and more importantly you need to know in advance how many threads will be created (or wait until they are all started before creating the latch.)

那么在什么情况下可能会优先使用锁存器呢?

So in what situation might the latch be preferable?

推荐答案

CountDown锁存器经常用于与您的示例完全相反。一般来说,你会有很多线程阻塞await(),当countown达到零时它们都会同时开始。

CountDown latch 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!

您也可以将其用作MPI风格的障碍,导致所有线程等待其他

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();
}

这一切都说,CountDown锁可以安全地使用,您的示例中显示了。

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

这篇关于CountDownLatch与Semaphore的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆