CompletableFuture

  • 异步编程利器:CompletableFuture详解
  • [ ] Java 8 CompletableFuture 教程

    1. public class FutureTest {
    2. public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
    3. UserInfoService userInfoService = new UserInfoService();
    4. MedalService medalService = new MedalService();
    5. long userId =666L;
    6. long startTime = System.currentTimeMillis();
    7. //调用用户服务获取用户基本信息
    8. CompletableFuture<UserInfo> completableUserInfoFuture = CompletableFuture.supplyAsync(() -> userInfoService.getUserInfo(userId));
    9. Thread.sleep(300); //模拟主线程其它操作耗时
    10. CompletableFuture<MedalInfo> completableMedalInfoFuture = CompletableFuture.supplyAsync(() -> medalService.getMedalInfo(userId));
    11. UserInfo userInfo = completableUserInfoFuture.get(2,TimeUnit.SECONDS);//获取个人信息结果
    12. MedalInfo medalInfo = completableMedalInfoFuture.get();//获取勋章信息结果
    13. System.out.println("总共用时" + (System.currentTimeMillis() - startTime) + "ms");
    14. }
    15. }

    CompletableFuture 吞异常的问题