CompletableFuture
admin
2024-01-30 06:06:19

之前的多线程处理

Runnable --> Void

Callable --> Future      (get() 阻塞等待结果,或者while一直等待结果)

现在的异步编程

等结果完成后,自动触发回调方法。

CompletableFunction

a) 提供要运行的任务

  • runAsync        无返回结果
  • supplyAsync   有返回结果

b)任务完成后触发

  • thenRun        完成任务时没有结果,然后接着运行下一个任务
  • thenAccept    完成任务时有结果,处理该结果不用返回数据。
  • thenApply      完成任务时有结果,处理改结果并返回新的数据。


​​​​​​​c) 处理执行流程中碰到的异常

  • exceptionally  当异常情况发生时,处理异常信息。
  • handle            数据和异常同时由handle函数处理。

Testing Code:

package com.coupang.flink;import org.junit.Test;import java.time.LocalDateTime;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;/*** description: TODO** @author adore.chen* @date 2022-11-18*/
public class CompletableFutureTest {@Testpublic void runAsync() {CompletableFuture completableFuture = CompletableFuture.runAsync(() -> {System.out.println("First Runnable Task ... at " + LocalDateTime.now());try {TimeUnit.MILLISECONDS.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}}).thenRun(() -> System.out.println("Second Runnable Task ... at " + LocalDateTime.now()));completableFuture.join();System.out.println("Main thread finished! ");}@Testpublic void runAsyncException() {CompletableFuture completableFuture = CompletableFuture.runAsync(() -> {System.out.println("First Runnable Task ... at " + LocalDateTime.now());throw new IllegalArgumentException("Unknown exception ...");}).thenRun(() -> System.out.println("Second Runnable Task ... at " + LocalDateTime.now())).exceptionally(e -> {System.out.println("meet some exception");e.printStackTrace(System.err);return null;});completableFuture.join();System.out.println("Main thread finished! ");}@Testpublic void supplyAsync() {CompletableFuture completableFuture = CompletableFuture.supplyAsync( () -> {System.out.println("First Callable Task ... at " + LocalDateTime.now());try {TimeUnit.MILLISECONDS.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}return "First Result";}).thenAccept(r -> {System.out.println("Second Callabe Task ... at " + LocalDateTime.now());System.out.println("Received result from First Callable: " + r);});completableFuture.join();System.out.println("Main Thread Finished");}@Testpublic void supplyAsyncResult() throws ExecutionException, InterruptedException {CompletableFuture completableFuture = CompletableFuture.supplyAsync( () -> {System.out.println("First Callable Task ... at " + LocalDateTime.now());try {TimeUnit.MILLISECONDS.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}return "First Result";}).thenApply(r -> {System.out.println("Second Callabe Task ... at " + LocalDateTime.now());System.out.println("Received result from First Callable: " + r);return "Second Task Result";});System.out.println("Main Thread Finished with Result: " + completableFuture.get());}public static void supplyAsyncHandle() throws ExecutionException, InterruptedException {CompletableFuture completableFuture = CompletableFuture.supplyAsync( () -> {System.out.println("First Callable Task ... at " + LocalDateTime.now());try {TimeUnit.MILLISECONDS.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}return "First Result";}).thenApply(r -> {System.out.println("Second Callabe Task ... at " + LocalDateTime.now());System.out.println("Received result from First Callable: " + r);return "Second Task Result";}).handle((data, e) -> {System.out.println("get result from first task, result: " + data);if (e != null) {e.printStackTrace();}return "handle over";});System.out.println("Main Thread Finished with Result: " + completableFuture.get());}@Testpublic void supplyAsyncHandleException() throws ExecutionException, InterruptedException {CompletableFuture completableFuture = CompletableFuture.supplyAsync( () -> {System.out.println("First Callable Task ... at " + LocalDateTime.now());throw new IllegalArgumentException("Unkown Exception !!!");}).thenApply(r -> {System.out.println("Second Callabe Task ... at " + LocalDateTime.now());System.out.println("Received result from First Callable: " + r);return "Second Task Result";}).handle((data, e) -> {System.out.println("get result from first task, result: " + data);if (e != null) {e.printStackTrace();}return "handle over";});System.out.println("Main Thread Finished with Result: " + completableFuture.get());}
}

相关内容

热门资讯

把音乐厅搬进喀斯特溶洞是什么体...   近日,一场融合多元艺术形式的洞穴音乐会在贵州省修文县举行,五百余名观众在喀斯特溶洞之中,感受了一...
教师专享福利!北京这些景区免票... 新京报讯 据首都教育消息,教师节将至,北京多家景区为老师们准备了专属免票福利!这份优惠合集已整理好,...
黑茶,喝的是一种境界与健康 在专门用来喝黑茶的茶具“飘逸杯”里,黑茶茶汤看起来并不像“黑茶”这个名字那样黑黢黢的一团。 玻璃器皿...
上海旅游节大巡游花车阵容抢先看... 2026上海旅游节大巡游9月12日外滩启幕,21辆全新主题花车携手21支境内外表演方队联袂登场,邀你...
原创 8... 上周门诊来了位 62 岁的张阿姨,得糖尿病快五年了,平时管嘴特别严,糖果、点心、甜饮料一概不碰,连水...