https://blog.51cto.com/u_16297326/13571760 总结: CompletableFuture 是 Java 中实现异步编程的强大工具,它提供了丰富的 API 来创建、组合和处理异步任务, 能够帮助开发者构建高性能、高响应性的应用程序。通过本文的详细介绍和代码示例, 读者应该对 CompletableFuture 的基本使用、链式调用、组合多个任务、异常处理以及实际应用等方面有了深入的了解。 在实际开发中,灵活运用 CompletableFuture 的特性,结合性能优化和最佳实践,能够有效提升应用程序的性能和用户体验。 随着 Java 技术的不断发展和应用场景的日益复杂,掌握 CompletableFuture 等异步编程技术对于 Java 开发者来说显得尤为重要。 七、实际应用案例:构建复杂的异步工作流 为了更好地理解 CompletableFuture 的实际应用,我们来看一个构建复杂异步工作流的案例。 假设我们需要开发一个电商订单处理系统,其中包含多个异步任务,如验证用户信息、检查库存、计算运费、处理支付等。 这些任务之间存在一定的依赖关系,需要合理地组合和处理。 // 验证用户信息 CompletableFuture validateUserAsync(String userId) { return CompletableFuture.supplyAsync(() -> { System.out.println("Validating user..."); // 模拟网络延迟 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } // 返回用户对象 return new User(userId); }); } // 检查库存 CompletableFuture checkInventoryAsync(Product product, int quantity) { return CompletableFuture.supplyAsync(() -> { System.out.println("Checking inventory for product: " + product.getId()); // 模拟网络延迟 try { Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } // 返回是否有足够库存 return product.getStock() >= quantity; }); } // 计算运费 CompletableFuture calculateShippingCostAsync(User user, double totalWeight) { return CompletableFuture.supplyAsync(() -> { System.out.println("Calculating shipping cost..."); // 模拟网络延迟 try { Thread.sleep(1200); } catch (InterruptedException e) { e.printStackTrace(); } // 根据用户地址和总重量计算运费 return totalWeight * 0.5; }); } // 处理支付 CompletableFuture processPaymentAsync(User user, double amount) { return CompletableFuture.supplyAsync(() -> { System.out.println("Processing payment..."); // 模拟网络延迟 try { Thread.sleep(1800); } catch (InterruptedException e) { e.printStackTrace(); } // 返回支付是否成功 return true; }); } // 构建订单处理工作流 public void processOrder(String userId, Product product, int quantity) { // 验证用户信息 CompletableFuture userFuture = validateUserAsync(userId); // 检查库存 CompletableFuture inventoryFuture = userFuture .thenCompose(user -> checkInventoryAsync(product, quantity)); // 计算运费 CompletableFuture shippingCostFuture = inventoryFuture .thenCompose(hasInventory -> { if (hasInventory) { return calculateShippingCostAsync(userFuture.join(), product.getWeight() * quantity); } else { return CompletableFuture.completedFuture(0.0); } }); // 处理支付 CompletableFuture paymentFuture = shippingCostFuture .thenCompose(shippingCost -> { double totalAmount = product.getPrice() * quantity + shippingCost; return processPaymentAsync(userFuture.join(), totalAmount); }); // 最终处理 paymentFuture .thenAccept(paymentSuccess -> { if (paymentSuccess) { System.out.println("Order processed successfully."); } else { System.out.println("Payment failed, order not processed."); } }) .exceptionally(ex -> { System.out.println("Error occurred during order processing: " + ex.getMessage()); return null; }) .join(); }