});intlen=3;// 调试:发生异常// 开关1:第4个是否发生异常// arr[3] = CompletableFuture.supplyAsync(()->{// var tn = Thread.currentThread().getName();// printWithTime("start: " + tn + ", i=OUT");/// if (makeEx) {// throw new RuntimeException("发生了异常...boom");// }...
importjava.util.concurrent.CompletableFuture; //展示 thenRun 、thenAccept 、 thenApply 、 exceptionally 等用法 @SpringBootTest publicclassAppTest2{ /* //thenRun 会在上一个 CompletableFuture 计算完成的时候执行一个 Runnable //Runnable 并不使用上一个 CompletableFuture 计算的结果。 //因此使用 thenRun ...
public static CompletableFuture<Void> runAsync(Runnable runnable,Executor executor) //有返回值,类似Future 可选择传入一个线程池 public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,Executor executor) 1.1 获得结...
publicstaticvoidmain(String[]args)throws ExecutionException,InterruptedException{CompletableFuture<String>completableFuture=newCompletableFuture();//自己开个线程去执行 执行完把结果告诉completableFuture即可newThread(()->{// 模拟执行耗时任务System.out.println("task doing...");try{Thread.sleep(3000);System....
4.CompletableFuture类的的使用 5.总结 1.Future类简介 我们之前在这篇文章JAVA并发编程——Callable接口和FutureTask简介和使用中说过,Future就是可以获得返回值的一个异步处理线程类。 在之前无论是继承Thread类还是实现Runnable接口,我们始终无法得到线程的返回值,但是Future就可以,Future是拥有返回值的线程,这样说我们...
CompletableFuture 提供了多种方法来组合异步任务: @SneakyThrowspublicvoidcombineTasks(){// 创建两个异步任务 future1 和 future2,分别返回字符串 "Hello" 和 "World"CompletableFuture<String>future1=CompletableFuture.supplyAsync(()->"Hello");CompletableFuture<String>future2=CompletableFuture.supplyAsync(()->...
水哥今天想聊聊 Java 的 CompletableFuture 类。该类自 JDK1.8 引入。水哥以 JDK21 为基础,首篇对 CompletableFuture 类代码进行分析总结,续篇会用具体示例代码来演示一下该类的用法。 CompletableFuture 实现了 Future 和 CompletionStage 接口。 public class CompletableFuture<T> implements Future<T>, CompletionStage...
CompletableFuture同时是一个构建块和一个框架,有大约50种不同的方法来组合,组合和执行异步计算步骤以及处理错误。 如此大的 API 可能会让人不知所措,但这些大多属于几个清晰而不同的用例。 3. 使用CompletableFuture作为简单的Future接口实例 首先,CompletableFuture类实现了 Future 接口,以便我们可以将其用作Future实...
CompletableFuture的方法如果以Async结尾,它会异步的执行(没有指定executor的情况下), 异步执行通过ForkJoinPool实现, 它使用守护线程去执行任务。 这是CompletableFuture的特性, 其它CompletionStage可以override这个默认的行为。 3、在前一个阶段上应用函数 下面这个例子使用前面#1的完成的CompletableFuture,#1返回结果为字符...
而如果我们想要动手进行优化的时候呢,就会涉及到串行处理改并行处理的问题。在JAVA中并行处理的能力支持已经相对完善,通过对CompletableFuture的合理利用,可以让我们面对这种聚合类处理的场景会更加的得心应手。 好啦,话不多说,接下来就让我们一起来品尝下JAVA中组合式并行处理这道饕餮大餐吧。