Java基础:并发小结

1 并发问题产生的根本原因

是因为并发程序中存在可变共享状态(的变量)。
另外,该可变共享状态的发现和管理有时非常困难,无法预料,所以使用Java并发特性时,一定要小心小心再小心,能不用就千万不要用。
注:可变共享状态:mutable shared state

2 CompletableFuture

2.1 生成一个CompletableFuture对象的静态方法

// 生成一个CompletableFuture<Void>
public static CompletableFuture<Void> runAsync(Runnable runnable) {...}
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor) {...}
// 生成一个CompletableFuture<U>
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {...}
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor) {...}

2.2 生成一个CompletableFuture对象的非静态方法(实例方法)

注:

  1. 以下方法,因为都是返回一个CompletableFuture对象,所以都可以链式调用
  2. 以下暂时忽略 带 Executor executor 参数的方法
// 同步
public CompletableFuture<Void> thenAccept(Consumer<? super T> action) {...}
// 异步
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action) {...}
// 同步
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> thenApply(Function<? super T,? extends U> fn) {...}
// 异步
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn) {...}

// 以下:“run”和“accept”是终结操作,⽽“apply”和“combine”则⽣成新 的承担负载(payload-bearing)的 CompletableFuture
// 同步
public CompletableFuture<Void> runAfterEither(CompletionStage<?> other,  Runnable action) {...}
// 异步
public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,  Runnable action) {...}
// 同步
public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other, Runnable action) {...}
// 异步
public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action) {...}
// 同步
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 CompletableFuture<Void> acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action) {...}
// 异步
public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action) {...}
// 同步
public <U> CompletableFuture<Void> thenAcceptBoth(CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action) {...}
// 异步
public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action) {...}
// 同步
public <U,V> CompletableFuture<V> thenCombine(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn) {...}
// 异步
public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn) {...}
posted @ 2022-04-01 16:52  mediocrep  阅读(22)  评论(0编辑  收藏  举报
既然选择了远方,便只顾风雨兼程!