假设我们有一个电商网站,我们需要同时调用多个外部服务来获取商品的价格、库存和评价数量,并在所有信息都获取成功后进行进一步的处理。
我们可以使用CompletableFuture来并发地调用这些外部服务,并在所有任务完成后进行处理。以下是一个具体的案例:
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CompletableFutureExample {
public static void main(String[] args) {
// 模拟调用外部服务获取商品价格的操作
CompletableFuture<Double> getPrice = CompletableFuture.supplyAsync(() -> {
try {
// 模拟远程调用,这里使用Thread.sleep来模拟耗时操作
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 99.99;
});
// 模拟调用外部服务获取商品库存的操作
CompletableFuture<Integer> getStock = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 10;
});
// 模拟调用外部服务获取商品评价数量的操作
CompletableFuture<Integer> getReviewCount = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 50;
});
// 所有任务都完成后进行处理
CompletableFuture<Void> allTasks = CompletableFuture.allOf(getPrice, getStock, getReviewCount);
allTasks.thenRun(() -> {
try {
double price = getPrice.get();
int stock = getStock.get();
int reviewCount = getReviewCount.get();
System.out.println("Price: $" + price);
System.out.println("Stock: " + stock);
System.out.println("Review Count: " + reviewCount);
// 进一步的处理...
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
});
// 等待所有任务完成
try {
allTasks.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
在这个例子中,我们使用supplyAsync
方法创建了三个CompletableFuture,分别模拟了调用外部服务获取商品价格、库存和评价数量的操作。然后,我们使用allOf
方法将所有任务组合在一起,并使用thenRun
方法在所有任务完成后进行处理。在处理中,我们通过get
方法获取每个任务的结果,并进行进一步的处理。
运行这个例子,你会看到以下输出:
Price: $99.99
Stock: 10
Review Count: 50
这说明我们成功地并发地调用了多个外部服务,并在所有任务完成后进行了进一步的处理。这种场景在需要同时获取多个任务结果并进行后续处理的情况下非常有用。