异步CompletableFuture简单使用

异步CompletableFuture简单使用
  1. runXXX方法都是没有返回结果的,supplyXXX都是有返回结果的。可以传入自定义的线程池,否则就用默认的线程池。**supplyAsync()**方法没有返回值。

    public static ExecutorService threadPool = Executors.newFixedThreadPool(10);
    
    public static void main(String[] args) {
        // 1、简单的执行异步任务
    	// 创建一个线程池
    CompletableFuture.runAsync(() -> {
        System.out.println("当前线程:" + Thread.currentThread().getId());
        int i = 10 / 2;
        System.out.println("运行结果:" + i);
    }, threadPool);
    }
    
  2. **supplyAsync()**完成回调与异常感知(不传入参数,执行完会返回一个参数)

    // 创建一个线程池
    public static ExecutorService threadPool = Executors.newFixedThreadPool(10);
    
    public static void main(String[] args) {
    // 2、完成回调与异常感知(不传入参数,执行完会返回一个参数)
    CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
        System.out.println("当前线程:" + Thread.currentThread().getId());
        int i = 10 / 0;
        System.out.println("运行结果:" + i);
        // 2.1执行完线程后返回的值
        return i;
    }, threadPool)
        .whenCompleteAsync((integer, throwable) ->{
        // 2.2可以打印返回值信息和异常信息
        System.out.println("integer = " + integer);
        System.out.println("throwable = " + throwable);
    })
        .exceptionally(throwable -> {
        // 2.3可以感知异常,同时返回默认值
        return 10;
    });
    
    try {
        //取得返回值内容
        System.out.println("future = " + future.get());
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
    }
    
  3. **handl()**最终处理

    public static ExecutorService threadPool = Executors.newFixedThreadPool(10);
    
    public static void main(String[] args) {
    // 3.方法执行后的处理
    CompletableFuture.supplyAsync(() -> {
        System.out.println("当前线程:" + Thread.currentThread().getId());
        int i = 10 / 2;
        System.out.println("运行结果:" + i);
        // 3.1执行完线程后返回的值
        return i;
    }, threadPool).handle((result, throwable) -> {
        //方法返回后对数据进行处理并且返回,result,throwable是执行过程中抛出的异常
        if (result != null) {
        //    如果有返回值结果,就会进入到这里
            return result * 2;
        }
        if (throwable != null) {
            //出现异常返回0
            return 0;
        }
        return 0;
    });
    }
    
  4. 线程串行化

    • thenRun(),只要上一步的任务执行完成,就开始执行thenRun(),带Async默认是异步操作。

    • thenAccept(),消费处理结果。接受上一步任务的处理结果,并消费处理,无返回值结果。

    • thenApply(),当一个线程依赖另一个线程时,获取上一个任务返回的结果,并返回当前任务的返回值。

      public static ExecutorService threadPool = Executors.newFixedThreadPool(10);
      
      public static void main(String[] args) {
      // 4、线程串行化,thenRunAsync无返回值
      //  第一个任务执行
      CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
          System.out.println("当前线程:" + Thread.currentThread().getId());
          int i = 10 / 2;
          System.out.println("运行结果:" + i);
          // 2.1执行完线程后返回的值
          return i;
      }, threadPool);
      
      // 4.1等第一个任务执行完成后,执行第二个任务
      // future.thenRunAsync(() -> {
      //     System.out.println("任务二启动了");
      // },threadPool);
      
      // 5、thenRunAsync无返回值 接受上一个的返回值结果,但是没有返回值出去
      future.thenAcceptAsync(result -> {
          System.out.println("result = " + result);
      });
      
      // 6、thenApplyAsync无返回值 接受上一个的返回值结果,有返回值出去
      future.thenApplyAsync(result -> {
          return result * 2;
      });
      }
      
    1. 两任务组合,两个都要执行
    • runAfterBoth():组合两个Future,不需要获取future的结果,只需要两个future处理完任务后,处理该任务。

    • thenAcceptBoth():组合两个Future,获取两个future的返回结果,然后处理任务,没有返回值。

    • thenCombine():组合两个Future,获取两个future的返回结果,并返回当前任务的返回值。

      public static void main(String[] args) {
          // 6、两任务都要完成
          // 6.1第一个任务
          CompletableFuture<Integer> future01 = CompletableFuture.supplyAsync(() -> {
              System.out.println("任务一线程start:" + Thread.currentThread().getId());
              int i = 10 / 2;
              System.out.println("运行结果:" + i);
              System.out.println("任务一线程end:" + Thread.currentThread().getId());
              // 2.1执行完线程后返回的值
              return i;
          }, threadPool);
      
          // 6.2第二个任务
          CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> {
              System.out.println("任务二线程start:" + Thread.currentThread().getId());
              System.out.println("任务二线程end:" + Thread.currentThread().getId());
              return "hello";
          }, threadPool);
      
          /**
           * 任务一线程start:11
           * 运行结果:5
           * 任务一线程end:11
           * 任务二线程start:12
           * 任务二线程end:12
           * 任务三线程start:14
           * 任务三线程end:14
           */
          //runAfterBoth():组合两个Future,不需要获取future的结果,只需要两个future处理完任务后,处理该任务。
          future01.runAfterBothAsync(future02, () -> {
              System.out.println("任务三线程start:" + Thread.currentThread().getId());
              System.out.println("任务三线程end:" + Thread.currentThread().getId());
          }, threadPool);
      
          /**
           * 任务一线程start:11
           * 运行结果:5
           * 任务一线程end:11
           * 任务二线程start:12
           * 任务二线程end:12
           * 任务三线程start:13
           * f1 = 5
           * f2 = hello
           * 任务三线程end:13
           */
          // thenAcceptBoth():组合两个Future,获取两个future的返回结果,然后处理任务,没有返回值。
          future01.thenAcceptBothAsync(future02, (f1ReturnValue, f2ReturnValue) -> {
              System.out.println("任务三线程start:" + Thread.currentThread().getId());
              System.out.println("f1ReturnValue = " + f1ReturnValue);
              System.out.println("f2ReturnValue = " + f2ReturnValue);
              System.out.println("任务三线程end:" + Thread.currentThread().getId());
          }, threadPool);
      
          /**
           * 任务一线程start:11
           * 运行结果:5
           * 任务一线程end:11
           * 任务二线程start:12
           * 任务二线程end:12
           * 任务三线程start:13
           * f1ReturnValue = 5
           * f2ReturnValue = hello
           * 任务三线程end:13
           * future3ReturnValue = 5hello
           */
          // thenCombine():组合两个Future,获取两个future的返回结果,并返回当前任务的返回值。
          CompletableFuture<String> future3ReturnValue = future01.thenCombineAsync(future02, (f1ReturnValue, f2ReturnValue) -> {
              System.out.println("任务三线程start:" + Thread.currentThread().getId());
              System.out.println("f1ReturnValue = " + f1ReturnValue);
              System.out.println("f2ReturnValue = " + f2ReturnValue);
              System.out.println("任务三线程end:" + Thread.currentThread().getId());
              return f1ReturnValue + f2ReturnValue;
          }, threadPool);
      
          try {
              System.out.println("future3ReturnValue = " + future3ReturnValue.get());
          } catch (InterruptedException | ExecutionException e) {
              e.printStackTrace();
          }
      }
      
    1. 两个任务组合,任意一个任务完成的时候,执行这个任务。

      • runAfterEither():两个任务有一个执行完成,不需要获取future的结果,处理任务,也没有返回值。

      • acceptEither():两个任务有一个执行完成,获取它的结果,处理任务,没有新的返回值。

      • applyToEither():两个任务有一个执行完成,获取它的的结果,处理任务,有新的返回值。

        public static ExecutorService threadPool = Executors.newFixedThreadPool(10);
        public static void main(String[] args) {
                // 7、两任务中任意一个完成
                // 7.1第一个任务
                CompletableFuture<Integer> future01 = CompletableFuture.supplyAsync(() -> {
                    System.out.println("任务一线程start:" + Thread.currentThread().getId());
                    int i = 10 / 2;
                    System.out.println("运行结果:" + i);
                    System.out.println("任务一线程end:" + Thread.currentThread().getId());
                    // 2.1执行完线程后返回的值
                    return i;
                }, threadPool);
        
                // 7.2第二个任务
                CompletableFuture<Integer> future02 = CompletableFuture.supplyAsync(() -> {
                    System.out.println("任务二线程start:" + Thread.currentThread().getId());
                    System.out.println("任务二线程end:" + Thread.currentThread().getId());
                    return 998;
                }, threadPool);
        
        
                /**
                 * 任务一线程start:11
                 * 运行结果:5
                 * 任务一线程end:11
                 * 任务二线程start:12
                 * 任务三线程start:14
                 * 任务三线程end:14
                 * 任务二线程end:12
                 */
                // - unAfterEither():两个任务有一个执行完成,不需要获取future的结果,处理任务,也没有返回值。
                future01.runAfterEitherAsync(future02,() -> {
                    System.out.println("任务三线程start:" + Thread.currentThread().getId());
                    System.out.println("任务三线程end:" + Thread.currentThread().getId());
                } , threadPool);
        
                /**
                 * 任务一线程start:11
                 * 运行结果:5
                 * 任务一线程end:11
                 * 任务二线程start:12
                 * 任务三线程start:13
                 * f1ReturnValue = 5
                 * 任务三线程end:13
                 * 任务二线程end:12
                 */
                // - acceptEither():两个任务有一个执行完成,获取它的结果,处理任务,没有新的返回值。
                //注意:前面两个任务的返回类型要一致,不然会报错。
                future01.acceptEitherAsync(future02,(returnValue) -> {
                    System.out.println("任务三线程start:" + Thread.currentThread().getId());
                    System.out.println("returnValue = " + returnValue);
                    System.out.println("任务三线程end:" + Thread.currentThread().getId());
                } , threadPool);
        
        
                /**
                 *任务一线程start:11
                 * 运行结果:5
                 * 任务一线程end:11
                 * 任务二线程start:12
                 * 任务二线程end:12
                 * 任务三线程start:13
                 * returnValue = 5
                 * 任务三线程end:13
                 * f3ReturnValue:500
                 */
                // - applyToEither():两个任务有一个执行完成,获取它的的结果,处理任务,有新的返回值。
                CompletableFuture<Integer> future03 = future01.applyToEitherAsync(future02, (returnValue) -> {
                    System.out.println("任务三线程start:" + Thread.currentThread().getId());
                    System.out.println("returnValue = " + returnValue);
                    System.out.println("任务三线程end:" + Thread.currentThread().getId());
                    return returnValue * 100;
                }, threadPool);
                try {
                    System.out.println("f3ReturnValue:" + future03.get());
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
                threadPool.shutdown();
            }
        
      1. 多任务组合

        • allOf():等待所有任务完成。
        • anyOf():只要一个任务完成。
        public static ExecutorService threadPool = Executors.newFixedThreadPool(10);
        public static void main(String[] args) {
            // 1、查询商品的图片信息!
            CompletableFuture<String> futureImg = CompletableFuture.supplyAsync(() -> {
                System.out.println("查询商品的图片信息!!");
                return "hello.jpg";
            }, threadPool);
        
            // 2、查询商品的属性!
            CompletableFuture<String> futureAttr = CompletableFuture.supplyAsync(() -> {
                System.out.println("查询商品的属性!!");
                return "黑色+256G";
            }, threadPool);
        
            // 3、查询商品的介绍!
            CompletableFuture<String> futureDesc = CompletableFuture.supplyAsync(() -> {
                System.out.println("查询商品的介绍!!");
                return "华为";
            }, threadPool);
        
            // allOf方法会等待所有的方法完成才继续下一步操作。
            CompletableFuture<Void> allOf = CompletableFuture.allOf(futureImg, futureAttr, futureDesc);
        
            try {
                //4、等待所有结果完成
                Void unused = allOf.get();
                System.out.println("unused = " + unused);
                threadPool.shutdown(); //关闭线程池
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        
            // anyOf方法会等待所有的方法完成才继续下一步操作。
            CompletableFuture<Void> anyOf = CompletableFuture.allOf(futureImg, futureAttr, futureDesc);
        
            try {
                anyOf.get();
                threadPool.shutdown(); //关闭线程池
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        
        }
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值