CountDownLatch 是 Java 并发包 java.util.concurrent
中的一个类,它允许一个或多个线程等待其他线程完成操作。
类型:
应用场景:
以下是一个简单的示例,展示如何在多线程程序中使用 CountDownLatch
:
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
final int numberOfThreads = 5;
CountDownLatch latch = new CountDownLatch(numberOfThreads);
for (int i = 0; i < numberOfThreads; i++) {
Thread thread = new Thread(new Worker(latch, i));
thread.start();
}
// 主线程在此等待所有子线程完成
latch.await();
System.out.println("All worker threads have finished.");
}
}
class Worker implements Runnable {
private final CountDownLatch latch;
private final int id;
public Worker(CountDownLatch latch, int id) {
this.latch = latch;
this.id = id;
}
@Override
public void run() {
try {
System.out.println("Thread " + id + " is working.");
Thread.sleep((long) (Math.random() * 1000));
System.out.println("Thread " + id + " has finished.");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 计数器减一
latch.countDown();
}
}
}
问题1:CountDownLatch 的计数器值设置错误
CountDownLatch
对象时设置的计数值等于实际需要等待的线程数。问题2:忘记调用 countDown() 方法
countDown()
方法。countDown()
方法。可以使用 finally
块来保证即使发生异常也能执行此操作。问题3:主线程提前结束
await()
方法之前结束,会导致程序提前退出。await()
方法后一直等待,直到所有子线程完成。通过合理使用 CountDownLatch
,可以有效管理和同步多线程程序的执行流程,提高程序的可靠性和效率。
领取专属 10元无门槛券
手把手带您无忧上云