当异步任务A和异步任务B存在关系,比如B需要A的结果数据,就需要编排控制。
- import java.util.concurrent.*;
-
-
- /**
- * future1没有返回值 future2有异步返回结果
- */
- public class FutureTest {
-
- public static ExecutorService executor = Executors.newFixedThreadPool(10);
-
- public static void main(String[] args) throws ExecutionException, InterruptedException {
- //异步对象
- System.out.println("main()-----start");
- CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
- System.out.println("future1无返回值异步任务测试哦");
- }, executor);
-
- CompletableFuture<Integer> future2 = CompletableFuture
- .supplyAsync(() -> {
- return 10 / 2;
- //return 10 / 0; //模拟算数异常
- }, executor)
- .whenComplete((result, exception) -> {
- System.out.println("future2链式获取结果是:" + result);
- if (exception != null) {
- System.out.println("future2链式获取到异常:" + exception);
- }
- })
- .exceptionally(throwable -> {
- System.out.println("future2处理异常,返回默认值");
- return 10;
- });
- System.out.println("future2结果是:" + future2.get());
-
-
- CompletableFuture<Integer> future3 = CompletableFuture
- .supplyAsync(() -> {
- return 10 / 2;
- }, executor)
- .handle((result, exception) -> {
- if (result != null) {
- System.out.println("handle处理返回结果");
- return result * 10;
- }
-
- if (exception != null) {
- return 0;
- }
- return 0;
- });
- System.out.println("future3结果是:" + future3.get());
-
- //run...是没有返回值的
- /**
- * 线程串行化
- * 1.thenRun.. 不能获取到上一步的执行结果
- * 2.thenAccept.. 能获取到上一步的返回值,但没有返回值
- * 3.thenApply.. 既能获取到上一步的返回值,有返回值
- */
- CompletableFuture<Void> future4 = CompletableFuture
- .supplyAsync(() -> {
- return 10 / 2;
- }, executor)
- .thenRunAsync(() -> {
- System.out.println("future4任务2启动了,无返回值");
- }, executor);
-
-
- CompletableFuture<Void> future5 = CompletableFuture
- .supplyAsync(() -> {
- return 10 / 2;
- }, executor)
- .thenAcceptAsync((res) -> {
- System.out.println("future5任务2启动了,能获取上一步值,但无返回值:" + res);
- });
-
- CompletableFuture<Integer> future6 = CompletableFuture
- .supplyAsync(() -> {
- return 10 / 2;
- }, executor)
- .thenApplyAsync(res -> {
- System.out.println("future6任务2启动了,有返回值:" + res);
- return res / 5;
- }, executor);
- System.out.println("future6最终返回值:" + future6.get());
- System.out.println("main()-----end");
- }
-
- }