目录
一、CompletableFuture源码中线程串行化方法
- 一、CompletableFuture源码中线程串行化方法
- 二、thenApply方法代码示例
- 三、thenAccept方法代码示例
- 四、thenRun方法代码示例
- 在CompletableFuture类中有以下方法:
-
thenApply方法:当一个线程依赖另一个线程时,获取上一个任务返回结果,并返回当前任务的返回值。
-
代码示例
package com.xz.thread.day1; import lombok.SneakyThrows; import java.util.concurrent.*; /** * @description: 线程串行化 * thenApply方法:当一个线程依赖另一个线程时,获取上一个任务返回结果,并返回当前任务的返回值。 * @author: xz * @create: 2022-08-23 */ public class Test8 { /** * 定义线程池 */ public static ExecutorService service = Executors.newFixedThreadPool(5); @SneakyThrows public static void main(String[] args) throws ExecutionException, InterruptedException { System.out.println("main start ..."); CompletableFuture future = CompletableFuture.supplyAsync(() -> { System.out.println("开启异步任务..."); int i = 10 % 2; return i; }, service).thenApplyAsync((res) -> { System.out.println("任务2启动了... 上一步的结果是:" + res); return res + 2; }, service); System.out.println("获取异步任务最终返回值:" + future.get()); System.out.println("main end ..."); } }
-
输出结果
-
thenAccept方法:接收任务的处理结果,并消费处理结果,无返回结果。
-
代码示例
package com.xz.thread.day1; import lombok.SneakyThrows; import java.util.concurrent.*; /** * @description: 线程串行化 * thenAccept方法:消费处理结果,接收任务的处理结果,并消费处理,无返回结果。 * @author: xz * @create: 2022-08-23 */ public class Test9 { /** * 定义线程池 */ public static ExecutorService service = Executors.newFixedThreadPool(3); @SneakyThrows public static void main(String[] args){ System.out.println("main start ..."); CompletableFuture future = CompletableFuture.supplyAsync(() -> { System.out.println("开启异步任务..."); int i = 10 % 2; return i; }, service).thenAcceptAsync((res) -> { System.out.println("任务2启动了... 上一步的结果是:" + res); }, service); System.out.println("获取异步任务返回值:" + future.get()); System.out.println("main end ..."); } }
-
输出结果
-
thenRun方法:只要上面的任务执行完成,就开始执行thenRun,只是处理完任务后,执行thenRun的后续操作。获取不到上个任务的执行结果,无返回值。
-
代码示例
package com.xz.thread.day1; import lombok.SneakyThrows; import java.util.concurrent.*; /** * @description: 线程串行化 * thenRun方法:获取不到上个任务的执行结果,无返回值。 * @author: xz * @create: 2022-08-23 */ public class Test10 { /** * 定义线程池 */ public static ExecutorService service = Executors.newFixedThreadPool(3); @SneakyThrows public static void main(String[] args) throws ExecutionException, InterruptedException { System.out.println("main start ..."); CompletableFuture future = CompletableFuture.supplyAsync(() -> { System.out.println("开启异步任务..."); int i = 10 % 2; return i; }, service).thenRun(() -> { System.out.println("任务2启动了..."); }); System.out.println("获取异步任务返回值:" + future.get()); System.out.println("main end ..."); } }
-
输出结果