使用
而不是
并发信号量 ?
据我所知,下面这些片段几乎是等价的:
信号灯
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种情况下不能重用闩锁,更重要的是,您需要预先知道将创建多少个线程(或者等到它们全部启动后再创建闩锁)
那么,在什么情况下,门闩更合适呢?