Java基础:并发小结
目录
- 1 并发问题产生的根本原因
- 2 CompletableFuture
- 2.1 生成一个CompletableFuture对象的静态方法
- 2.2 生成一个CompletableFuture对象的非静态方法(实例方法)
1 并发问题产生的根本原因
是因为并发程序中存在可变共享状态(的变量)。
另外,该可变共享状态的发现和管理有时非常困难,无法预料,所以使用Java并发特性时,一定要小心小心再小心,能不用就千万不要用。
注:可变共享状态:mutable shared state
2 CompletableFuture
2.1 生成一个CompletableFuture对象的静态方法
// 生成一个CompletableFuture
public static CompletableFuture runAsync(Runnable runnable) {...}
public static CompletableFuture runAsync(Runnable runnable, Executor executor) {...}
// 生成一个CompletableFuture
public static CompletableFuture supplyAsync(Supplier supplier) {...}
public static CompletableFuture supplyAsync(Supplier supplier, Executor executor) {...}
2.2 生成一个CompletableFuture对象的非静态方法(实例方法)
注:
- 以下方法,因为都是返回一个CompletableFuture对象,所以都可以链式调用
- 以下暂时忽略 带 Executor executor 参数的方法
// 同步
public CompletableFuture thenAccept(Consumer<? super T> action) {...}
// 异步
public CompletableFuture thenAcceptAsync(Consumer<? super T> action) {...}
// 同步
public CompletableFuture thenCompose(Function<? super T, ? extends CompletionStage> fn) {...}
// 异步
public CompletableFuture thenComposeAsync(Function<? super T, ? extends CompletionStage> fn) {...}
// 同步
public CompletableFuture thenApply(Function<? super T,? extends U> fn) {...}
// 异步
public CompletableFuture thenApplyAsync(Function<? super T,? extends U> fn) {...}
// 以下:“run”和“accept”是终结操作,?“apply”和“combine”则?成新 的承担负载(payload-bearing)的 CompletableFuture
// 同步
public CompletableFuture runAfterEither(CompletionStage<?> other, Runnable action) {...}
// 异步
public CompletableFuture runAfterEitherAsync(CompletionStage<?> other, Runnable action) {...}
// 同步
public CompletableFuture runAfterBoth(CompletionStage<?> other, Runnable action) {...}
// 异步
public CompletableFuture runAfterBothAsync(CompletionStage<?> other, Runnable action) {...}
// 同步
public CompletableFuture applyToEither(CompletionStage<? extends T> other, Function<? super T, U> fn) {...}
// 异步
public CompletableFuture applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T, U> fn) {...}
// 同步
public CompletableFuture acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action) {...}
// 异步
public CompletableFuture acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action) {...}
// 同步
public CompletableFuture thenAcceptBoth(CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action) {...}
// 异步
public CompletableFuture thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action) {...}
// 同步
public CompletableFuture thenCombine(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn) {...}
// 异步
public CompletableFuture thenCombineAsync(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn) {...}