java 中创建线程并使用 countdownlatch 等待多线程完成,核心做法是实例化一个计数器为线程数量的 countdownlatch 对象,在子线程任务结束时调用其 countdown() 方法,主线程通过调用 await() 阻塞等待直到计数器归零。具体实现时,需将 latch 实例传递给每个线程,确保所有线程执行完毕后主线程才能继续处理结果。

如何初始化 CountDownLatch 并传递给线程
初始化 CountDownLatch 时需要传入一个整数参数,该参数代表需要等待的事件数量,通常等于创建的线程数。将这个实例作为参数传递给每个新创建的线程或 Runnable 任务,确保它们共享同一个锁存器对象。这样,每个线程在执行完自己的逻辑后,都能通知锁存器减少计数。

import java.util.concurrent.CountDownLatch;
public class ThreadWithLatch {
public static void main(String[] args) throws InterruptedException {
int threadCount = 3;
// 1. 初始化 CountDownLatch,计数器为线程数量
CountDownLatch latch = new CountDownLatch(threadCount);
for (int i = 0; i {
try {
System.out.println("Thread " + taskId + " is running");
// 模拟业务逻辑
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 2. 任务结束后调用 countDown()
latch.countDown();
}
}).start();
}
// 3. 主线程等待所有线程完成
latch.await();
System.out.println("All threads have finished.");
}
}
如何处理线程异常与 await 超时
在使用 await() 时,建议指定超时时间以避免主线程无限期阻塞。如果某个线程因异常未能调用 countDown(),主线程将在超时后继续执行,防止死锁。同时,应在子线程的 finally 块中调用 countDown(),确保即使发生异常也能正确释放锁存器。主线程捕获 InterruptedException 以处理等待过程中的中断情况。
FilePond 是一个 JavaScript 文件上传库,支持通过拖拽、粘贴和 API 方式处理文件、目录、URL 和 Data URI。它包含内置的图像优化功能、异步分块上传功能,并提供了适用于 React、Vue、Angular 和 Svelte 的适配器。

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class ThreadWithTimeout {
public static void main(String[] args) {
int threadCount = 3;
CountDownLatch latch = new CountDownLatch(threadCount);
for (int i = 0; i {
try {
System.out.println("Task " + taskId + " executing");
if (taskId == 1) {
throw new RuntimeException("Simulated error");
}
Thread.sleep(2000);
} catch (Exception e) {
System.err.println("Task " + taskId + " failed: " + e.getMessage());
} finally {
// 无论成功或失败,都减少计数
latch.countDown();
}
}).start();
}
try {
// 等待最多 5 秒
boolean completed = latch.await(5, TimeUnit.SECONDS);
if (completed) {
System.out.println("All tasks completed within timeout.");
} else {
System.out.println("Timeout reached, some tasks may still be running.");
}
} catch (InterruptedException e) {
System.err.println("Main thread interrupted while waiting.");
}
}
}
当某个线程未调用 countDown 时会发生什么
如果某个线程由于逻辑错误未在 finally 块中调用 countDown(),CountDownLatch 的计数器将无法归零。此时,主线程调用 await() 将永久阻塞,导致程序挂起。为避免此问题,必须确保每个线程路径(包括异常路径)都执行 countDown()。若使用超时机制,主线程将在超时后恢复执行,但可能检测到部分任务未完成的状态。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










