之前须要异步执行一个任务时,通常是用Thread或者线程池Executor去建立。若是须要返回值,则是调用Executor.submit获取Future。可是多个线程存在依赖组合,咱们又能怎么办?可以使用同步组件CountDownLatch、CyclicBarrier等;其实有简单的方法,就是用CompletableFuturejavascript
//使用内置线程ForkJoinPool.commonPool(),根据supplier构建执行任务 public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) //指定自定义线程,根据supplier构建执行任务 public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
//使用内置线程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 public static <U> CompletableFuture<U> completedFuture(U value)
任务完成则运行action,不关心上一个任务的结果,无返回值java
public CompletableFuture<Void> thenRun(Runnable action) public CompletableFuture<Void> thenRunAsync(Runnable 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
public CompletableFuture<Void> thenAccept(Consumer<? super T> action) public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> 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
public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn) public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> 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
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
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
//第一个任务完成再运行other,fn再依赖消费两个任务的结果,无返回值 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
//第一个任务完成再运行other,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
public CompletableFuture<Void> runAfterEither(CompletionStage<?> other, Runnable action) public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other, Runnable 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
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) 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
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) 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
public CompletableFuture<T> exceptionally(Function<Throwable, ? extends T> fn)
CompletableFuture<Integer> first = CompletableFuture .supplyAsync(() -> { if (true) { throw new RuntimeException("main error!"); } return "hello world"; }) .thenApply(data -> 1) .exceptionally(e -> { e.printStackTrace(); // 异常捕捉处理,前面两个处理环节的平常都能捕获 return 0; });
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
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
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();
// 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
// 任务是否执行完成 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
Java 多线程一直是面试时候的重点,也是能力提高的重要体现,如何作到波澜不惊,从容面对,须要咱们对其中的内容融汇贯通,小编这里也对应总结了一份多线程-并发编程的思惟导图,须要的朋友能够看看,关注公众号:麒麟改bug,还能够领取一份包含了Java基础、Java集合容器、Java异常、并发编程、JVM、Spring、Spring MVC、Spring Boot、Spring Cloud、MyBatis、Redis、MySQL数据库、消息中间件MQ与RabbitMQ、Dubbo、Linux、Tomcat、ZooKeeper、Netty、 架构设计&分布式&数据结构与算法等等,都是互联网大厂的面试真题,已经有粉丝靠这份PDF拿下众多大厂的offer。面试