CountDownLatch 与信号量 [英] CountDownLatch vs. Semaphore

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

问题描述

使用有什么好处吗

java.util.concurrent.CountdownLatch

代替

java.util.concurrent.信号量?

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

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?

推荐答案

CountDownLatch 经常用于与您的示例完全相反的情况.通常,您会在 await() 上阻塞许多线程,当计数达到零时,它们会同时启动.

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!

您也可以将其用作 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();
}

话虽如此,CountDownLatch 可以按照您在示例中显示的方式安全地使用.

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

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

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