说明
1、JDK 8中引入了 CompletableFuture 类,实现了Future和CompletionStage接口.
为异步编程提供了一些列方法,如supplyAsync、runAsync和thenApplyAsync等。
2、功能是可以让两个或者多个进行运算来产生结果。
实例
/** * @author mghio * @since 2021-08-01 */ public class CompletableFutureDemo { public static CompletableFuture<String> doOneThing() { return CompletableFuture.supplyAsync(() -> { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return "doOneThing"; }); } public static CompletableFuture<String> doOtherThing(String parameter) { return CompletableFuture.supplyAsync(() -> { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return parameter + " " + "doOtherThing"; }); } public static void main(String[] args) throws ExecutionException, InterruptedException { StopWatch stopWatch = new StopWatch("CompletableFutureDemo"); stopWatch.start(); // 异步执行版本 testCompletableFuture(); stopWatch.stop(); System.out.println(stopWatch); } private static void testCompletableFuture() throws InterruptedException, ExecutionException { // 先执行 doOneThing 任务,后执行 doOtherThing 任务 CompletableFuture<String> resultFuture = doOneThing().thenCompose(CompletableFutureDemo::doOtherThing); // 获取任务结果 String doOneThingResult = resultFuture.get(); // 获取执行结果 System.out.println("DoOneThing and DoOtherThing execute finished. result = " + doOneThingResult); } }
Java 函数式编程范式与面向对象编程范式的比较
Spring Boot项目启动Jar包冲突,如何快速排查并解决?
子类如何通过父类方法修改父类私有属性?
在Java编程中,如果你想在检测到学生ID重复时停止后续代码的执行,可以使用return语句或者抛出异常来实现。以下是两种常见的方法:方法一:使用return语句这种方法适用于在方法内部检测到重复ID时,直接返回,停止后续代码的执行。public void processStudent(Student student) { if (isStudentIdDuplicate(student.getId())) { System.out.println("学生ID已存在,停止处理。")
在 Android Fragment 中,如何最佳地调用 Activity 方法?
HttpServletResponseWrapper加密接口返回值时如何避免中文乱码?