这篇文章主要介绍“如何使用Java异步编程”,在日常操作中,相信很多人在如何使用Java异步编程问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”如何使用Java异步编程”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
隆回网站制作公司哪家好,找成都创新互联!从网页设计、网站建设、微信开发、APP开发、成都响应式网站建设公司等网站项目制作,到程序开发,运营维护。成都创新互联从2013年成立到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选成都创新互联。
//使用内置线程ForkJoinPool.commonPool(),根据supplier构建执行任务 public static CompletableFuture supplyAsync(Supplier supplier) //指定自定义线程,根据supplier构建执行任务 public static CompletableFuture supplyAsync(Supplier supplier, Executor executor)
//使用内置线程ForkJoinPool.commonPool(),根据runnable构建执行任务 public static CompletableFuturerunAsync(Runnable runnable) //指定自定义线程,根据runnable构建执行任务 public static CompletableFuture runAsync(Runnable runnable, Executor executor)
使用示例
ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuturerFuture = CompletableFuture .runAsync(() -> System.out.println("hello siting"), executor); //supplyAsync的使用 CompletableFuture 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 public static CompletableFuture completedFuture(U value)
任务完成则运行action,不关心上一个任务的结果,无返回值
public CompletableFuturethenRun(Runnable action) public CompletableFuture thenRunAsync(Runnable action) public CompletableFuture thenRunAsync(Runnable action, Executor executor)
使用示例
CompletableFuturefuture = CompletableFuture .supplyAsync(() -> "hello siting", executor) .thenRunAsync(() -> System.out.println("OK"), executor); executor.shutdown(); --------输出结果-------- OK
public CompletableFuturethenAccept(Consumer action) public CompletableFuture thenAcceptAsync(Consumer action) public CompletableFuture thenAcceptAsync(Consumer action, Executor executor)
使用示例
ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuturefuture = CompletableFuture .supplyAsync(() -> "hello siting", executor) .thenAcceptAsync(System.out::println, executor); executor.shutdown(); --------输出结果-------- hello siting
public CompletableFuture thenApply(Function fn) public CompletableFuture thenApplyAsync(Function fn) public CompletableFuture thenApplyAsync(Function fn, Executor executor)
使用示例
ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuturefuture = CompletableFuture .supplyAsync(() -> "hello world", executor) .thenApplyAsync(data -> { System.out.println(data); return "OK"; }, executor); System.out.println(future.join()); executor.shutdown(); --------输出结果-------- hello world OK
类似thenApply(区别是thenCompose的返回值是CompletionStage,thenApply则是返回 U),提供该方法为了和其他CompletableFuture任务更好地配套组合使用
public CompletableFuture thenCompose(Function> fn) public CompletableFuture thenComposeAsync(Function> fn) public CompletableFuture thenComposeAsync(Function> fn, Executor executor)
使用示例
//第一个异步任务,常量任务 CompletableFuturef = CompletableFuture.completedFuture("OK"); //第二个异步任务 ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture 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
public CompletableFuturerunAfterBoth(CompletionStage other, Runnable action) public CompletableFuture runAfterBothAsync(CompletionStage other, Runnable action) public CompletableFuture runAfterBothAsync(CompletionStage other, Runnable action, Executor executor)
使用示例
//第一个异步任务,常量任务 CompletableFuturefirst = CompletableFuture.completedFuture("hello world"); ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture future = CompletableFuture //第二个异步任务 .supplyAsync(() -> "hello siting", executor) // () -> System.out.println("OK") 是第三个任务 .runAfterBothAsync(first, () -> System.out.println("OK"), executor); executor.shutdown(); --------输出结果-------- OK
//第一个任务完成再运行other,fn再依赖消费两个任务的结果,无返回值 public CompletableFuturethenAcceptBoth(CompletionStage other, BiConsumer action) //两个任务异步完成,fn再依赖消费两个任务的结果,无返回值 public CompletableFuture thenAcceptBothAsync(CompletionStage other, BiConsumer action) //两个任务异步完成(第二个任务用指定线程池执行),fn再依赖消费两个任务的结果,无返回值 public CompletableFuture thenAcceptBothAsync(CompletionStage other, BiConsumer action, Executor executor)
使用示例
//第一个异步任务,常量任务 CompletableFuturefirst = CompletableFuture.completedFuture("hello world"); ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture 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
//第一个任务完成再运行other,fn再依赖消费两个任务的结果,有返回值 public CompletableFuturethenCombine(CompletionStage other, BiFunction fn) //两个任务异步完成,fn再依赖消费两个任务的结果,有返回值 public CompletableFuture thenCombineAsync(CompletionStage other, BiFunction fn) //两个任务异步完成(第二个任务用指定线程池执行),fn再依赖消费两个任务的结果,有返回值 public CompletableFuture thenCombineAsync(CompletionStage other, BiFunction fn, Executor executor)
使用示例
//第一个异步任务,常量任务 CompletableFuturefirst = CompletableFuture.completedFuture("hello world"); ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture 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
public CompletableFuturerunAfterEither(CompletionStage other, Runnable action) public CompletableFuture runAfterEitherAsync(CompletionStage other, Runnable action) public CompletableFuture runAfterEitherAsync(CompletionStage other, Runnable action, Executor executor)
使用示例
//第一个异步任务,休眠1秒,保证最晚执行晚 CompletableFuturefirst = CompletableFuture.supplyAsync(()->{ try{ Thread.sleep(1000); }catch (Exception e){} System.out.println("hello world"); return "hello world"; }); ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture 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
public CompletableFutureacceptEither(CompletionStage other, Consumer action) public CompletableFuture acceptEitherAsync(CompletionStage other, Consumer action, Executor executor) public CompletableFuture acceptEitherAsync(CompletionStage other, Consumer action, Executor executor)
使用示例
//第一个异步任务,休眠1秒,保证最晚执行晚 CompletableFuturefirst = CompletableFuture.supplyAsync(()->{ try{ Thread.sleep(1000); }catch (Exception e){} return "hello world"; }); ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture future = CompletableFuture //第二个异步任务 .supplyAsync(() -> "hello siting", executor) // data -> System.out.println(data) 是第三个任务 .acceptEitherAsync(first, data -> System.out.println(data) , executor); executor.shutdown(); --------输出结果-------- hello siting
public CompletableFuture applyToEither(CompletionStage other, Function fn) public CompletableFuture applyToEitherAsync(CompletionStage other, Function fn) public CompletableFuture applyToEitherAsync(CompletionStage other, Function fn, Executor executor)
使用示例
//第一个异步任务,休眠1秒,保证最晚执行晚 CompletableFuturefirst = CompletableFuture.supplyAsync(()->{ try{ Thread.sleep(1000); }catch (Exception e){} return "hello world"; }); ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture 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
public CompletableFutureexceptionally(Function fn)
如果之前的处理环节有异常问题,则会触发exceptionally的调用相当于 try...catch
使用示例
CompletableFuturefirst = CompletableFuture .supplyAsync(() -> { if (true) { throw new RuntimeException("main error!"); } return "hello world"; }) .thenApply(data -> 1) .exceptionally(e -> { e.printStackTrace(); // 异常捕捉处理,前面两个处理环节的日常都能捕获 return 0; });
相比exceptionally而言,即可处理上一环节的异常也可以处理其正常返回值
public CompletableFuture handle(BiFunction fn) public CompletableFuture handleAsync(BiFunction fn) public CompletableFuture handleAsync(BiFunction fn, Executor executor)
使用示例
CompletableFuturefirst = 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与handle的区别在于,它不参与返回结果的处理,把它当成监听器即可
即使异常被处理,在CompletableFuture外层,异常也会再次复现
使用whenCompleteAsync时,返回结果则需要考虑多线程操作问题,毕竟会出现两个线程同时操作一个结果
public CompletableFuturewhenComplete(BiConsumer action) public CompletableFuture whenCompleteAsync(BiConsumer action) public CompletableFuture whenCompleteAsync(BiConsumer action, Executor executor)
使用示例
CompletableFuturefirst = 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
public static CompletableFutureallOf(CompletableFuture... cfs) public static CompletableFuture