import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
class Order {
private String orderInfo;
public Order(String orderInfo) {
this.orderInfo = orderInfo;
}
public String getOrderInfo() {
return orderInfo;
}
}
public class AsyncTasks {
public static CompletableFuture<Order> getUserOrder() {
// 获取用户信息的异步任务
CompletableFuture<User> getUserFuture = CompletableFuture.supplyAsync(() -> {
// 模拟获取用户信息的耗时操作
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new User("John");
});
// 在获取用户信息任务完成后,执行获取订单列表的任务
return getUserFuture.thenApplyAsync(user -> {
// 模拟根据用户信息获取订单列表的耗时操作
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new Order("Order for " + user.getName());
});
}
public static void main(String[] args) {
CompletableFuture<Order> orderCompletableFuture = getUserOrder();
try {
Order order = orderCompletableFuture.get();
System.out.println(order.getOrderInfo());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
方法及原理说明
- CompletableFuture.supplyAsync:
- 该方法用于异步执行一个有返回值的任务。在代码中,
CompletableFuture.supplyAsync(() -> {...})
创建了一个异步任务来获取用户信息。这里的 supplyAsync
方法接受一个 Supplier
接口的实现,该实现会在一个新的线程中执行。
- thenApplyAsync:
- 该方法用于在
CompletableFuture
完成后,对其结果进行转换操作,并异步执行该转换操作。在代码中,getUserFuture.thenApplyAsync(user -> {...})
表示在 getUserFuture
任务(获取用户信息的任务)完成后,将用户信息作为参数传递给 thenApplyAsync
中的函数式接口。这个函数式接口会异步执行,根据用户信息获取订单列表并返回。
thenApplyAsync
方法接受一个 Function
接口的实现,该实现会在 getUserFuture
完成后被调用。通过这种链式调用,实现了先执行获取用户信息的任务,再在该任务完成后执行获取订单列表的任务。