本文共 14710 字,大约阅读时间需要 49 分钟。
以前需要异步执行一个任务时,一般是用Thread或者线程池Executor去创建。如果需要返回值,则是调用Executor.submit获取Future。但是多个线程存在依赖组合,我们又能怎么办?可使用同步组件CountDownLatch、CyclicBarrier等;其实有简单的方法,就是用CompeletableFuture
//使用内置线程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 无返回值,输出nullSystem.out.println(rFuture.join());//阻塞等待String name = future.join();System.out.println(name);executor.shutdown(); // 线程池需要关闭--------输出结果--------hello sitingnullhello siting
//有时候是需要构建一个常量的CompletableFuturepublic static CompletableFuture completedFuture(U value)
public CompletableFuturethenRun(Runnable action)public CompletableFuture thenRunAsync(Runnable action)//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)//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) //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 worldOK
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 worldOK
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并行完成后执行action,action再依赖消费两个任务的结果,无返回值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,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 sitingOK
public CompletableFuturerunAfterEither(CompletionStage other, Runnable action) public CompletableFuture runAfterEitherAsync(CompletionStage other, Runnable action)//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 sitingOK
public CompletableFutureacceptEither(CompletionStage other, Consumer action)public CompletableFuture acceptEitherAsync(CompletionStage other, Consumer action, Executor executor) //action用指定线程池执行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) //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 sitingOK
public CompletableFutureexceptionally(Function fn)
CompletableFuturefirst = CompletableFuture .supplyAsync(() -> { if (true) { throw new RuntimeException("main error!"); } return "hello world"; }) .thenApply(data -> 1) .exceptionally(e -> { e.printStackTrace(); // 异常捕捉处理,前面两个处理环节的日常都能捕获 return 0; });
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 morenull
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
CompletableFuturefuture = CompletableFuture .allOf(CompletableFuture.completedFuture("A"), CompletableFuture.completedFuture("B"));//全部任务都需要执行完future.join();CompletableFuture
// mayInterruptIfRunning 无影响;如果任务未完成,则返回异常public boolean cancel(boolean mayInterruptIfRunning) //任务是否取消public boolean isCancelled()
CompletableFuturefuture = 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任务取消后:truejava.util.concurrent.CancellationException at java.util.concurrent.CompletableFuture.cancel(CompletableFuture.java:2276) at Test.main(Test.java:25)0
// 任务是否执行完成public boolean isDone()//阻塞等待 获取返回值public T join()// 阻塞等待 获取返回值,区别是get需要返回受检异常public T get()//等待阻塞一段时间,并获取返回值public T get(long timeout, TimeUnit unit)//未完成则返回指定valuepublic T getNow(T valueIfAbsent)//未完成,使用value作为任务执行的结果,任务结束。需要future.get获取public boolean complete(T value)//未完成,则是异常调用,返回异常结果,任务结束public boolean completeExceptionally(Throwable ex)//判断任务是否因发生异常结束的public boolean isCompletedExceptionally()//强制地将返回值设置为value,无论该之前任务是否完成;类似completepublic void obtrudeValue(T value)//强制地让异常抛出,异常返回,无论该之前任务是否完成;类似completeExceptionallypublic void obtrudeException(Throwable ex)
CompletableFuturefuture = 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
转载地址:http://irgkz.baihongyu.com/