使用线程池配合使用:
开发中为什么使用线程池
*减低资源的消耗:通过重复利用已经创建好的线程减低线程的创建和销毁带来的损耗。
*提高响应速度:线程池中的线程数没有超过线程池的最大上限时,有的线程处于等待分配任务的状态,当任务来时无需创建新的线程就能执行。
*提高线程的客观理性:线程池会根据当前系统特点对池内的线程进行优化处理,减少创建和销毁线程带来的系统开销,无限的创建和销毁线程不仅消耗系统资源,还降低系统的稳定性,使用线程池进行统一分配。
CompletableFuture:
1.1、创建异步对象
CompletableFuture 提供了四个静态方法来创建一个异步操作。
//一个参数的是创建一个线程去执行任务,两个参数的是提供一个线程池去执行任务
//runAsync方法不支持返回值。
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)
1.2、计算完成时回调方法
当CompletableFuture的计算结果完成,或者抛出异常的时候,可以执行特定的Action。主要是下面的方法:
whenComplete可以处理正常和异常的计算结果,提供两个参数第一个参数是正常处理的结果,第二个参数是异常。(正常处理时异常为null,发生异常时,结果为null。我们可以根据这两个参数去编写相应的处理方法)
exceptionally处理异常情况。BiConsumer<? super T,? super Throwable>可以定义处理业务,提供一个异常类参数,有返回值。
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);
public CompletableFuture<T> exceptionally(Function<Throwable,? extends T> fn);
whenComplete 和 whenCompleteAsync 的区别:
有Async的表示在选一个线程去执行业务,没有的则说明在本线程接着执行业务。
1.3 线程串行化方法
thenApply 方法:获取前一个任务的处理结果,再进行处理,返回新的结果
Function<? super T,? extends U>
T:上一个任务返回结果的类型
U:当前任务的返回值类型
thenAccept方法:处理结果。接收前一个任务的处理结果,进行业务处理,无返回结果。
thenRun方法:前一个任务执行完,执行thenRun
带有Async默认是异步执行的。这里所谓的异步指的是不在当前线程内执行。
//获取前一个任务的结果,进行处理,返回新的结果。
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)
//处理结果。接收前一个任务的处理结果,进行业务,无返回结果
public CompletionStage<Void> thenAccept(Consumer<? super T> action);
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action);
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action,Executor executor);
//前一个任务执行完成,然后执行thenRun
public CompletionStage<Void> thenRun(Runnable action);
public CompletionStage<Void> thenRunAsync(Runnable action);
public CompletionStage<Void> thenRunAsync(Runnable action,Executor executor);
2.4 多任务组合
//allOf:等待所有任务完成
public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs);
//anyOf:只要有一个任务完成
public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs);