CompletableFuture 介绍
1 2 3 4 5 6 7 8 9 10 |
CompletableFuture<Long> future = new CompletableFuture<>(); //手动正常完成和异常完成 future.complete(System.currentTimeMillis()); future.completeExceptionally(new RuntimeException("error occur")); future.completeAsync(()-> return "value"); //thenAccept 提供Consumer future.thenAccept(System.out::println); //异常处理 future.exceptionally((ex) -> { ex.printStackTrace(); return 1234L;}); |
1 2 3 4 5 6 7 8 9 |
CompletableFuture<Long> future = CompletableFuture.supplyAsync(supplier); CompletableFuture<Long> future2 = CompletableFuture.supplyAsync(supplier); CompletableFuture<Long> future3 = CompletableFuture.supplyAsync(()->{throw new RuntimeException("run error");}); CompletableFuture.allOf(future, future2, future3).thenAccept(v->{ System.out.println(future.join()); System.out.println(future2.join()); }).exceptionally(ex->{ex.printStackTrace(); return null; }); |
Posted in: java基础
Comments are closed.