使用有什么好处吗
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的情况下不能重用闩锁之外,更重要的是,您需要提前知道将创建多少个线程(或者等到它们全部启动后再创建闩锁)。
那么在什么情况下闩锁是可取的呢?
最佳答案
CountDownLatch
通常与您的示例完全相反。通常,您会阻塞await()
的许多线程,这些线程将在计数达到零时同时启动。
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样式的“屏障”,该屏障使所有线程在继续执行之前等待其他线程 catch 特定点。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
。关于java - CountDownLatch与信号量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/184147/