Java 线程池

Java 线程相关

  1. 继承 Thread
  2. 实现 Runable 接口 无返回值 无参数
  3. 实现 Callable 接口 有返回值 无参数
  4. 线程池

Java 异步任务

力量:$E=mc^2$

这里需要先说明一下:在标准的 Java CompletableFuture API 中, thenApplyAsync

下面我来详细解释 thenApplythenAcceptthenApplyAsync 的区别。

1. thenApply vs thenAccept:对结果的处理方式不同

它们都是在前一个异步任务完成后执行的回调,核心区别在于对任务结果的处理和返回

方法 函数式接口 入参 返回值 用途
thenApply Function<T, R> 有(上一个任务的结果) (处理后的新结果) 转换结果,例如将字符串转换为它的长度。
thenAccept Consumer<T> 有(上一个任务的结果) (CompletableFuture<Void>) 消费结果,执行一个动作但不产生新值,例如打印结果。

代码示例对比:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello");

// thenApply:有入参,有返回值,用于转换
CompletableFuture<Integer> applyFuture = future.thenApply(s -> s.length()); 
// applyFuture 的结果是 Integer 类型的 5

// thenAccept:有入参,无返回值,用于消费
CompletableFuture<Void> acceptFuture = future.thenAccept(s -> System.out.println(s)); 
// acceptFuture 没有结果,只是打印 "Hello"

还有一个 thenRun,它不接收上一个任务的结果,也不返回任何值,只用于在任务完成后执行一个动作。

2. thenApply vs thenApplyAsync:执行线程不同

thenApplythenApplyAsync 功能完全相同,都是转换上一个任务的结果。唯一的区别在于执行回调任务的线程

同理,thenAccept 也有对应的异步版本 thenAcceptAsync

总结