使用有什么好处吗
java.util.concurrent.CountdownLatch
代替
java.util.concurrent.Semaphore吗?
据我所知,以下片段几乎是等效的:
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的情况下不能重用闩锁之外,更重要的是,您需要提前知道将创建多少个线程(或者等到它们全部启动后再创建闩锁)。
那么在什么情况下闩锁会更可取呢?