关于java:基础篇异步编程不会我教你啊CompletableFutureJDK18

前言

以前须要异步执行一个工作时,个别是用Thread或者线程池Executor去创立。如果须要返回值,则是调用Executor.submit获取Future。然而多个线程存在依赖组合,咱们又能怎么办?可应用同步组件CountDownLatch、CyclicBarrier等;其实有简略的办法,就是用CompeletableFuture

  • 线程工作的创立
  • 线程工作的串行执行
  • 线程工作的并行执行
  • 解决工作后果和异样
  • 多任务的简略组合
  • 勾销执行线程工作
  • 工作后果的获取和实现与否判断

关注公众号,一起交换,微信搜一搜: 潜行前行

github地址,感激star

1 创立异步线程工作

依据supplier创立CompletableFuture工作

//应用内置线程ForkJoinPool.commonPool(),依据supplier构建执行工作
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
//指定自定义线程,依据supplier构建执行工作
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)

依据runnable创立CompletableFuture工作

//应用内置线程ForkJoinPool.commonPool(),依据runnable构建执行工作
public static CompletableFuture<Void> runAsync(Runnable runnable)
//指定自定义线程,依据runnable构建执行工作
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
  • 应用示例

    ExecutorService executor = Executors.newSingleThreadExecutor();
    CompletableFuture<Void> rFuture = CompletableFuture
       .runAsync(() -> System.out.println("hello siting"), executor);
    //supplyAsync的应用
    CompletableFuture<String> future = CompletableFuture
       .supplyAsync(() -> {
           System.out.print("hello ");
           return "siting";
       }, executor);
    
    //阻塞期待,runAsync 的future 无返回值,输入null
    System.out.println(rFuture.join());
    //阻塞期待
    String name = future.join();
    System.out.println(name);
    executor.shutdown(); // 线程池须要敞开
    --------输入后果--------
    hello siting
    null
    hello siting

    常量值作为CompletableFuture返回

    //有时候是须要构建一个常量的CompletableFuture
    public static <U> CompletableFuture<U> completedFuture(U value)

2 线程串行执行

工作实现则运行action,不关怀上一个工作的后果,无返回值

public CompletableFuture<Void> thenRun(Runnable action)
public CompletableFuture<Void> thenRunAsync(Runnable action)
//action用指定线程池执行
public CompletableFuture<Void> thenRunAsync(Runnable action, Executor executor)
  • 应用示例

    CompletableFuture<Void> future = CompletableFuture
       .supplyAsync(() -> "hello siting", executor)
       .thenRunAsync(() -> System.out.println("OK"), executor);
    executor.shutdown();
    --------输入后果--------
    OK

工作实现则运行action,依赖上一个工作的后果,无返回值

public CompletableFuture<Void> thenAccept(Consumer<? super T> action)
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action)
//action用指定线程池执行
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action, Executor executor)
  • 应用示例

    ExecutorService executor = Executors.newSingleThreadExecutor();
    CompletableFuture<Void> future = CompletableFuture
       .supplyAsync(() -> "hello siting", executor)
       .thenAcceptAsync(System.out::println, executor);
    executor.shutdown();
    --------输入后果--------
    hello siting

工作实现则运行fn,依赖上一个工作的后果,有返回值

public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn)    
//fn用指定线程池执行
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor)
  • 应用示例

    ExecutorService executor = Executors.newSingleThreadExecutor();
    CompletableFuture<String> future = CompletableFuture
       .supplyAsync(() -> "hello world", executor)
       .thenApplyAsync(data -> {
           System.out.println(data); return "OK";
       }, executor);
    System.out.println(future.join());
    executor.shutdown();
    --------输入后果--------
    hello world
    OK

    thenCompose – 工作实现则运行fn,依赖上一个工作的后果,有返回值

  • 相似thenApply(区别是thenCompose的返回值是CompletionStage,thenApply则是返回 U),提供该办法为了和其余CompletableFuture工作更好地配套组合应用

    public <U> CompletableFuture<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn) 
    public <U> CompletableFuture<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn)
    public <U> CompletableFuture<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn,
       Executor executor)        
  • 应用示例

    //第一个异步工作,常量工作
    CompletableFuture<String> f = CompletableFuture.completedFuture("OK");
    //第二个异步工作
    ExecutorService executor = Executors.newSingleThreadExecutor();
    CompletableFuture<String> future = CompletableFuture
       .supplyAsync(() -> "hello world", executor)
       .thenComposeAsync(data -> {
           System.out.println(data); return f; //应用第一个工作作为返回
       }, executor);
    System.out.println(future.join());
    executor.shutdown();
    --------输入后果--------
    hello world
    OK

3 线程并行执行

两个CompletableFuture并行执行完,而后执行action,不依赖上两个工作的后果,无返回值

public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other, Runnable action)
public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action)
public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action, Executor executor)
  • 应用示例

    //第一个异步工作,常量工作
    CompletableFuture<String> first = CompletableFuture.completedFuture("hello world");
    ExecutorService executor = Executors.newSingleThreadExecutor();
    CompletableFuture<Void> future = CompletableFuture
       //第二个异步工作
       .supplyAsync(() -> "hello siting", executor)
       // () -> System.out.println("OK") 是第三个工作
       .runAfterBothAsync(first, () -> System.out.println("OK"), executor);
    executor.shutdown();
    --------输入后果--------
    OK

两个CompletableFuture并行执行完,而后执行action,依赖上两个工作的后果,无返回值

//调用方工作和other并行实现后执行action,action再依赖生产两个工作的后果,无返回值
public <U> CompletableFuture<Void> thenAcceptBoth(CompletionStage<? extends U> other,
        BiConsumer<? super T, ? super U> action)
//两个工作异步实现,fn再依赖生产两个工作的后果,无返回值,应用默认线程池
public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,
        BiConsumer<? super T, ? super U> action)  
//两个工作异步实现,fn(用指定线程池执行)再依赖生产两个工作的后果,无返回值                
public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,
        BiConsumer<? super T, ? super U> action, Executor executor) 
  • 应用示例

    //第一个异步工作,常量工作
    CompletableFuture<String> first = CompletableFuture.completedFuture("hello world");
    ExecutorService executor = Executors.newSingleThreadExecutor();
    CompletableFuture<Void> future = CompletableFuture
       //第二个异步工作
       .supplyAsync(() -> "hello siting", executor)
       // (w, s) -> System.out.println(s) 是第三个工作
       .thenAcceptBothAsync(first, (s, w) -> System.out.println(s), executor);
    executor.shutdown();
    --------输入后果--------
    hello siting

两个CompletableFuture并行执行完,而后执行fn,依赖上两个工作的后果,有返回值

//调用方工作和other并行实现后,执行fn,fn再依赖生产两个工作的后果,有返回值
public <U,V> CompletableFuture<V> thenCombine(CompletionStage<? extends U> other, 
        BiFunction<? super T,? super U,? extends V> fn)
//两个工作异步实现,fn再依赖生产两个工作的后果,有返回值,应用默认线程池
public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other,
        BiFunction<? super T,? super U,? extends V> fn)   
//两个工作异步实现,fn(用指定线程池执行)再依赖生产两个工作的后果,有返回值        
public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other,
        BiFunction<? super T,? super U,? extends V> fn, Executor executor)         
  • 应用示例

    //第一个异步工作,常量工作
    CompletableFuture<String> first = CompletableFuture.completedFuture("hello world");
    ExecutorService executor = Executors.newSingleThreadExecutor();
    CompletableFuture<String> future = CompletableFuture
       //第二个异步工作
       .supplyAsync(() -> "hello siting", executor)
       // (w, s) -> System.out.println(s) 是第三个工作
       .thenCombineAsync(first, (s, w) -> {
           System.out.println(s);
           return "OK";
       }, executor);
    System.out.println(future.join());
    executor.shutdown();
    --------输入后果--------
    hello siting
    OK

4 线程并行执行,谁先执行完则谁触发下一工作(二者选其最快)

上一个工作或者other工作实现, 运行action,不依赖前一工作的后果,无返回值

public CompletableFuture<Void> runAfterEither(CompletionStage<?> other, Runnable action)   
public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other, Runnable action)
//action用指定线程池执行
public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,
        Runnable action, Executor executor)
  • 应用示例

    //第一个异步工作,休眠1秒,保障最晚执行晚
    CompletableFuture<String> first = CompletableFuture.supplyAsync(()->{
        try{ Thread.sleep(1000); }catch (Exception e){}
        System.out.println("hello world");
        return "hello world";
    });
    ExecutorService executor = Executors.newSingleThreadExecutor();
    CompletableFuture<Void> future = CompletableFuture
       //第二个异步工作
       .supplyAsync(() ->{
           System.out.println("hello siting");
           return "hello siting";
       } , executor)
       //() ->  System.out.println("OK") 是第三个工作
       .runAfterEitherAsync(first, () ->  System.out.println("OK") , executor);
    executor.shutdown();
    --------输入后果--------
    hello siting
    OK

上一个工作或者other工作实现, 运行action,依赖最先实现工作的后果,无返回值

public CompletableFuture<Void> acceptEither(CompletionStage<? extends T> other,
        Consumer<? super T> action)
public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other,
        Consumer<? super T> action, Executor executor)       
//action用指定线程池执行
public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other,
        Consumer<? super T> action, Executor executor)     
  • 应用示例

    //第一个异步工作,休眠1秒,保障最晚执行晚
    CompletableFuture<String> first = CompletableFuture.supplyAsync(()->{
        try{ Thread.sleep(1000);  }catch (Exception e){}
        return "hello world";
    });
    ExecutorService executor = Executors.newSingleThreadExecutor();
    CompletableFuture<Void> future = CompletableFuture
       //第二个异步工作
       .supplyAsync(() -> "hello siting", executor)
       // data ->  System.out.println(data) 是第三个工作
       .acceptEitherAsync(first, data ->  System.out.println(data) , executor);
    executor.shutdown();
    --------输入后果--------
    hello siting        

上一个工作或者other工作实现, 运行fn,依赖最先实现工作的后果,有返回值

public <U> CompletableFuture<U> applyToEither(CompletionStage<? extends T> other,
        Function<? super T, U> fn) 
public <U> CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T> other,
        Function<? super T, U> fn)         
//fn用指定线程池执行
public <U> CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T> other,
        Function<? super T, U> fn, Executor executor)         
  • 应用示例

    //第一个异步工作,休眠1秒,保障最晚执行晚
    CompletableFuture<String> first = CompletableFuture.supplyAsync(()->{
        try{ Thread.sleep(1000);  }catch (Exception e){}
        return "hello world";
    });
    ExecutorService executor = Executors.newSingleThreadExecutor();
    CompletableFuture<String> future = CompletableFuture
       //第二个异步工作
       .supplyAsync(() -> "hello siting", executor)
       // data ->  System.out.println(data) 是第三个工作
       .applyToEitherAsync(first, data ->  {
           System.out.println(data);
           return "OK";
       } , executor);
    System.out.println(future);
    executor.shutdown();
    --------输入后果--------
    hello siting
    OK

5 解决工作后果或者异样

exceptionally-解决异样

public CompletableFuture<T> exceptionally(Function<Throwable, ? extends T> fn)
  • 如果之前的解决环节有异样问题,则会触发exceptionally的调用相当于 try…catch
  • 应用示例

    CompletableFuture<Integer> first = CompletableFuture
       .supplyAsync(() -> {
           if (true) {
               throw new RuntimeException("main error!");
           }
           return "hello world";
       })
       .thenApply(data -> 1)
       .exceptionally(e -> {
           e.printStackTrace(); // 异样捕获解决,后面两个解决环节的日常都能捕捉
           return 0;
       });

handle-工作实现或者异样时运行fn,返回值为fn的返回

  • 相比exceptionally而言,即可解决上一环节的异样也能够解决其失常返回值

    public <U> CompletableFuture<U> handle(BiFunction<? super T, Throwable, ? extends U> fn) 
    public <U> CompletableFuture<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn) 
    public <U> CompletableFuture<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn, 
       Executor executor)        
  • 应用示例

    CompletableFuture<Integer> first = CompletableFuture
       .supplyAsync(() -> {
           if (true) { throw new RuntimeException("main error!"); }
           return "hello world";
       })
       .thenApply(data -> 1)
       .handleAsync((data,e) -> {
           e.printStackTrace(); // 异样捕获解决
           return data;
       });
    System.out.println(first.join());
    --------输入后果--------
    java.util.concurrent.CompletionException: java.lang.RuntimeException: main error!
        ... 5 more
    null

whenComplete-工作实现或者异样时运行action,有返回值

  • whenComplete与handle的区别在于,它不参加返回后果的解决,把它当成监听器即可
  • 即便异样被解决,在CompletableFuture外层,异样也会再次复现
  • 应用whenCompleteAsync时,返回后果则须要思考多线程操作问题,毕竟会呈现两个线程同时操作一个后果

    public CompletableFuture<T> whenComplete(BiConsumer<? super T, ? super Throwable> action) 
    public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action) 
    public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action,
       Executor executor)        
  • 应用示例

    CompletableFuture<AtomicBoolean> first = CompletableFuture
       .supplyAsync(() -> {
           if (true) {  throw new RuntimeException("main error!"); }
           return "hello world";
       })
       .thenApply(data -> new AtomicBoolean(false))
       .whenCompleteAsync((data,e) -> {
           //异样捕获解决, 然而异样还是会在外层复现
           System.out.println(e.getMessage());
       });
    first.join();
    --------输入后果--------
    java.lang.RuntimeException: main error!
    Exception in thread "main" java.util.concurrent.CompletionException: java.lang.RuntimeException: main error!
        ... 5 more

6 多个工作的简略组合

public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)
public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs)


  • 应用示例

     CompletableFuture<Void> future = CompletableFuture
       .allOf(CompletableFuture.completedFuture("A"),
               CompletableFuture.completedFuture("B"));
    //全副工作都须要执行完
    future.join();
    CompletableFuture<Object> future2 = CompletableFuture
       .anyOf(CompletableFuture.completedFuture("C"),
               CompletableFuture.completedFuture("D"));
    //其中一个工作行完即可
    future2.join();

8 勾销执行线程工作

// mayInterruptIfRunning 无影响;如果工作未实现,则返回异样
public boolean cancel(boolean mayInterruptIfRunning) 
//工作是否勾销
public boolean isCancelled()
  • 应用示例

    CompletableFuture<Integer> future = CompletableFuture
       .supplyAsync(() -> {
           try { Thread.sleep(1000);  } catch (Exception e) { }
           return "hello world";
       })
       .thenApply(data -> 1);
    
    System.out.println("工作勾销前:" + future.isCancelled());
    // 如果工作未实现,则返回异样,须要对应用exceptionally,handle 对后果解决
    future.cancel(true);
    System.out.println("工作勾销后:" + future.isCancelled());
    future = future.exceptionally(e -> {
        e.printStackTrace();
        return 0;
    });
    System.out.println(future.join());
    --------输入后果--------
    工作勾销前:false
    工作勾销后:true
    java.util.concurrent.CancellationException
        at java.util.concurrent.CompletableFuture.cancel(CompletableFuture.java:2276)
        at Test.main(Test.java:25)
    0

9 工作的获取和实现与否判断

// 工作是否执行实现
public boolean isDone()
//阻塞期待 获取返回值
public T join()
// 阻塞期待 获取返回值,区别是get须要返回受检异样
public T get()
//期待阻塞一段时间,并获取返回值
public T get(long timeout, TimeUnit unit)
//未实现则返回指定value
public T getNow(T valueIfAbsent)
//未实现,应用value作为工作执行的后果,工作完结。须要future.get获取
public boolean complete(T value)
//未实现,则是异样调用,返回异样后果,工作完结
public boolean completeExceptionally(Throwable ex)
//判断工作是否因产生异样完结的
public boolean isCompletedExceptionally()
//强制地将返回值设置为value,无论该之前工作是否实现;相似complete
public void obtrudeValue(T value)
//强制地让异样抛出,异样返回,无论该之前工作是否实现;相似completeExceptionally
public void obtrudeException(Throwable ex) 
  • 应用示例

    CompletableFuture<Integer> future = CompletableFuture
       .supplyAsync(() -> {
           try { Thread.sleep(1000);  } catch (Exception e) { }
           return "hello world";
       })
       .thenApply(data -> 1);
    
    System.out.println("工作实现前:" + future.isDone());
    future.complete(10);
    System.out.println("工作实现后:" + future.join());
    --------输入后果--------
    工作实现前:false
    工作实现后:10

欢送指注释中谬误