gpt4 book ai didi

java - CountDownLatch 与信号量

转载 作者:IT老高 更新时间:2023-10-28 11:35:41 26 4
gpt4 key购买 nike

使用有什么好处

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。)

那么在什么情况下闩锁更可取?

最佳答案

CountDownLatch 经常用于与您的示例完全相反的情况。通常,您会在 await() 上阻塞许多线程,这些线程会在 countown 达到零时同时启动。

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com