[英]Parallellize a for loop in Java using multi-threading
我是 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);
});
});
假設,您想要 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();
}
如果您使用的是並行流,您仍然可以通過創建自己的 ForkJoinPool 來控制線程。
List<Long> aList = LongStream.rangeClosed(firstNum, lastNum).boxed()
.collect(Collectors.toList());
ForkJoinPool customThreadPool = new ForkJoinPool(4);
long actualTotal = customThreadPool.submit(
() -> aList.parallelStream().reduce(0L, Long::sum)).get();
在此站點上,對它的描述非常好。 https://www.baeldung.com/java-8-parallel-streams-custom-threadpool
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.