使用有什么好处吗
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:倒计时锁存器
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 的情况下,闩锁不能被重用,更重要的是,您需要提前知道将创建多少线程(或者等到它们都启动后再创建闩锁。)
那么在什么情况下闩锁可能更可取呢?