【发布时间】:2010-09-16 02:19:18
【问题描述】:
使用有什么好处
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 的情况下,latch 不能被重用,更重要的是你需要提前知道将创建多少线程(或者等到它们都启动后再创建 latch。)
那么在什么情况下闩锁更可取?
【问题讨论】:
标签: java multithreading concurrency semaphore countdownlatch