ComputableFuture并行调用



我想并行运行10个API。每个API都返回一些值。当值的总数等于100时,我想停止,即如果我在获得所有API的结果之前获得100个结果,我不想等待所有10个API。所以我想在循环中使用CompletableFuture.anyOf()并返回,但我无法找到正确的语法。此外,是否有其他有效的方法可以做到这一点?

请回复。

提前感谢!

您可以使用CountDownLatch

ExecutorService executor = Executors.newFixedThreadPool(10);
List<Integer> results = new ArrayList<>();
int maxResults = 100;
CountDownLatch latch = new CountDownLatch(maxResults);
for (int i = 0; i < 10; ++i) {
int apiNumber = i;
executor.execute(() -> {
while (results.size() < maxResults) {
try {
Thread.sleep(new Random().nextInt(1000));
System.out.println("API-" + apiNumber + " call");
int[] newValues = new Random().ints(0, 10).limit(new Random().nextInt(10)).toArray(); // API call
for (int value : newValues) {
synchronized (results) {
if (results.size() < maxResults) {
results.add(value);
latch.countDown();
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
latch.await();
System.out.println("The results have been calculated (" + results.size() + ")");

executor.shutdown();

或相位

ExecutorService executor = Executors.newFixedThreadPool(10);
List<Integer> results = new ArrayList<>();
int maxResults = 100;
Phaser phaser = new Phaser(1);
phaser.register();
for (int i = 0; i < 10; ++i) {
int apiNumber = i;
executor.execute(() -> {
while (results.size() < maxResults) {
try {
Thread.sleep(new Random().nextInt(1000));
System.out.println("API-" + apiNumber + " call");
int[] newValues = new Random().ints(0, 10).limit(new Random().nextInt(10)).toArray(); // API call
for (int value : newValues) {
synchronized (results) {
results.add(value);
if (results.size() >= maxResults) {
phaser.arrive();
break;
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
phaser.arriveAndAwaitAdvance();
System.out.println("The results have been calculated (" + results.size() + ")");
executor.shutdown();

最新更新