我对java很陌生,我想使用执行器服务或使用java中的任何其他方法并行化嵌套for循环。我想创建一些固定数量的线程,这样CPU就不会完全被线程占用。
for(SellerNames sellerNames : sellerDataList) {
for(String selleName : sellerNames) {
//getSellerAddress(sellerName)
//parallize this task
}
}
sellerDataList 的大小 = 1000,sellerNames 的大小 = 5000。
现在我想创建 10 个线程,并将相同的任务块平均分配给每个线程。对于第 i 个 sellerDataList,第一个线程应该获取 500 个名称的地址,第二个线程应该获取接下来 500 个名称的地址,依此类推。
完成这项工作的最佳方法是什么?
有两种方法可以让它并行运行:Streams 和 Executors。
使用流
你可以使用并行流,剩下的交给jvm。在这种情况下,您对何时发生的情况没有太多控制权。另一方面,您的代码将易于阅读和维护:
sellerDataList.stream().forEach(sellerNames -> {
Stream<String> stream = StreamSupport.stream(sellerNames.spliterator(), true); // true means use parallel stream
stream.forEach(sellerName -> {
getSellerAddress(sellerName);
});
});
使用ExecutorService
假设您需要 5 个线程,并且希望能够等到任务完成。然后您可以使用具有 5 个线程的固定线程池并使用Future
-s 这样你就可以等到它们完成。
final ExecutorService executor = Executors.newFixedThreadPool(5); // it's just an arbitrary number
final List<Future<?>> futures = new ArrayList<>();
for (SellerNames sellerNames : sellerDataList) {
for (final String sellerName : sellerNames) {
Future<?> future = executor.submit(() -> {
getSellerAddress(sellerName);
});
futures.add(future);
}
}
try {
for (Future<?> future : futures) {
future.get(); // do anything you need, e.g. isDone(), ...
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)