FutureTask同时实现了Runable和Future接口
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
而FutureTask既然实现了这两个接口,那么肯定会有两个接口所对应的功能
正因为有FutureTask的这些缺点,CompletableFuture才会出现
CompletableFuture能够更好地结果这些问题
CompletableFuture 提供了四个静态方法来创建一个异步操作
//runAsync方法不支持返回值
public static CompletableFuture<Void> runAsync(Runnable runnable)
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
//supplyAsync可以支持返回值
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
其中带有Executor参数的方法是可以自己指定线程池的
其中runAsync没有返回值
public T get() throws InterruptedException, ExecutionException
public T get(long timeout, TimeUnit unit)
public T getNow(T valueIfAbsent)
public T join()
public boolean complete(T value)
public <U> CompletableFuture<U> thenApply(
Function<? super T,? extends U> fn) {
return uniApplyStage(null, fn);
}
public <U> CompletableFuture<U> handle(
BiFunction<? super T, Throwable, ? extends U> fn) {
return uniHandleStage(null, fn);
}
public CompletableFuture<Void> thenRun(Runnable action)
public CompletableFuture<Void> thenAccept(Consumer<? super T> action)
public <U> CompletableFuture<U> thenApply(
Function<? super T,? extends U> fn) {
return uniApplyStage(null, fn);
}
带了Async的方法表示的是:会重新在线程池中启动一个线程来执行任务
public <U> CompletableFuture<U> applyToEither
public <U> CompletableFuture<U> applyToEitherAsync
public CompletableFuture<Void> acceptEither
public CompletableFuture<Void> acceptEitherAsync
public CompletableFuture<Void> runAfterEither
public CompletableFuture<Void> runAfterEitherAsync
public <U,V> CompletableFuture<V> thenCombine
public <U> CompletableFuture<Void> thenAcceptBoth
public CompletableFuture<Void> runAfterBoth
public static CompletableFuture<Void> allOf
public static CompletableFuture<Object> anyOf
public CompletableFuture<T> whenComplete
public CompletableFuture<T> exceptionally
public <U> CompletableFuture<U> handle
void accept(T t, U u)
和普通消费者不一样,BiConsumer可以传入两个参数
R apply(T t, U u)
与普通Function不同,可以传入两个参数
boolean test(T t, U u)
和普通断言接口不一样,BiPredication可以传入两个参数
笔记参考
https://blog.csdn.net/TZ845195485/article/details/114692426
https://www.yuque.com/liuyanntes/sibb9g/fhqqge