import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class BulkDataProcessing {
// 模拟大批量数据处理任务
public static void processData(int id) {
System.out.println("Processing data batch: " + id + " by thread: " + Thread.currentThread().getName());
try {
// 模拟处理时间
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) {
int totalBatches = 100; // 总数据批次
int threadPoolSize = 10; // 线程池大小
ExecutorService executorService = Executors.newFixedThreadPool(threadPoolSize);
// 提交任务到线程池
for (int i = 0; i < totalBatches; i++) {
final int batchId = i;
executorService.submit(() -> processData(batchId));
}
// 关闭线程池并等待所有任务完成
executorService.shutdown();
try {
if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException e) {
executorService.shutdownNow();
}
System.out.println("All data batches processed.");
}
}
processData(int id)
方法:
Thread.sleep(1000)
模拟处理时间。main
方法:
totalBatches
和线程池的大小 threadPoolSize
。Executors.newFixedThreadPool(threadPoolSize)
创建一个固定大小的线程池。executorService.submit()
提交任务到线程池中,每个任务都会调用 processData
方法来处理一批数据。executorService.shutdown()
关闭线程池,并使用 awaitTermination
等待所有任务完成。如果在指定时间内没有完成,则强制关闭线程池。线程池的作用:
异常处理:
processData
方法中捕获 InterruptedException
并恢复线程的中断状态。main
方法中捕获 InterruptedException
并确保线程池能够正确关闭。这个示例展示了如何使用 Java 的多线程机制来高效地处理大批量数据。
上一篇:java 数据类型
下一篇:java数组转为字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站