在 Java 中处理大量数据(如 500 条数据,每次处理 100 条)时,可以使用 多线程 来提高处理效率。以下是几种常见的实现方式,结合线程池和分批处理逻辑,确保代码高效且易于维护。
一、使用线程池分批处理数据
1. 核心思路
- 将 500 条数据分成 5 批,每批 100 条。
- 使用线程池(如
ExecutorService
)并发处理每批数据。 - 等待所有任务完成后,继续后续操作。
2. 实现代码
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class BatchProcessor {
public static void main(String[] args) {
// 模拟 500 条数据
List<Integer> dataList = new ArrayList<>();
for (int i = 1; i <= 500; i++) {
dataList.add(i);
}
// 创建线程池(固定大小为 5)
ExecutorService executor = Executors.newFixedThreadPool(5);
// 分批处理数据
int batchSize = 100;
List<Future<?>> futures = new ArrayList<>();
for (int i = 0; i < dataList.size(); i += batchSize) {
// 获取当前批次的数据
List<Integer> batch = dataList.subList(i, Math.min(i + batchSize, dataList.size()));
// 提交任务到线程池
Future<?> future = executor.submit(() -> processBatch(batch));
futures.add(future);
}
// 等待所有任务完成
for (Future<?> future : futures) {
try {
future.get(); // 阻塞直到任务完成
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
// 关闭线程池
executor.shutdown();
System.out.println("所有批次处理完成!");
}
/**
* 处理每批数据的方法
*/
private static void processBatch(List<Integer> batch) {
System.out.println("开始处理批次: " + batch);
// 模拟处理逻辑
for (Integer data : batch) {
System.out.println("处理数据: " + data);
try {
Thread.sleep(100); // 模拟耗时操作
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("批次处理完成: " + batch);
}
}
3. 代码说明
- 线程池:使用
Executors.newFixedThreadPool(5)
创建固定大小的线程池,确保最多同时处理 5 个批次。 - 分批逻辑:通过
subList
方法将数据分成每批 100 条。 - 任务提交:使用
executor.submit
提交任务,返回Future
对象以便后续等待任务完成。 - 任务完成:通过
future.get()
阻塞等待所有任务完成。