看起来很冗长,但是您可以尝试以下方法。该
runAsync()方法将使列表块并行运行。
private void test(List<Object> list, int chunkSize) throws ExecutionException, InterruptedException { AtomicInteger prev = new AtomicInteger(0); List<CompletableFuture> futures = new ArrayList<>(); IntStream.range(1, (int) (chunkSize * (Math.ceil(Math.abs(list.size() / (double) chunkSize))))) .filter(i -> i % chunkSize == 0 || i == list.size()) .forEach(i -> { List<Object> chunk = list.subList(prev.get(), i); futures.add(CompletableFuture.runAsync(() -> invokeList(chunk))); prev.set(i); }); CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get();}private void invokeList(List<Object> list) { System.out.println("Invoked for: " + list);}我 为30个 整数 列表 运行,其 块大小为5, 如下所示:
public static void main(String[] args) throws ExecutionException, InterruptedException { List<Object> list = IntStream.range(0, 30).mapToObj(i1 -> (Object) String.valueOf(i1)).collect(Collectors.toList()); int chunkSize = 5; new Test().test(list, chunkSize);}输出 :
Invoked for: [15, 16, 17, 18, 19]Invoked for: [0, 1, 2, 3, 4]Invoked for: [5, 6, 7, 8, 9]Invoked for: [10, 11, 12, 13, 14]Invoked for: [20, 21, 22, 23, 24]



