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());}
}

相关内容

热门资讯

新质新格局,景芝白酒再次点亮黄... 11月18日,备受瞩目的2025年第六届中国白酒黄淮核心产区高质量发展峰会在淄博举办。本届峰会以“新...
今日播出|丝路陕茶 千年留香 播出时间:农林卫视《农村大市场》11月19日22:05 丝路陕茶 千年留香 陕西是我国最早种茶、出产...
纠结有什么好吃的零食品牌推荐?... 在快节奏的现代生活中,零食早已超越了单纯的充饥角色,转而成为我们慰藉味蕾、补充能量、甚至分享快乐的重...
吃巧克力能缓解甲状腺相关疲劳? 一、甲状腺相关疲劳的核心成因 要判断巧克力能否缓解甲状腺相关疲劳,首先需要明确这种疲劳的根源。甲状腺...
暖乎乎的酒酿南瓜丸子羹,一口甜... 秋冬最治愈的家常甜汤,必须提名酒酿南瓜丸子羹!金黄的南瓜丸子软乎乎,裹着清甜的酒酿汤汁,一口下去暖到...