Java8并发新特性CompletableFuture怎么使用

发布时间:2022-06-06 09:46:15 作者:iii
来源:亿速云 阅读:208

Java8并发新特性CompletableFuture怎么使用

Java 8引入了CompletableFuture类,作为Future接口的增强版,提供了更强大的异步编程能力。CompletableFuture不仅支持异步任务的执行,还允许开发者通过链式调用的方式处理任务的结果,极大地简化了并发编程的复杂性。本文将详细介绍CompletableFuture的使用方法。

1. CompletableFuture简介

CompletableFutureFuture接口的实现类,提供了丰富的API来处理异步任务的结果。与传统的Future相比,CompletableFuture具有以下优势:

2. 创建CompletableFuture

2.1 使用supplyAsync创建

supplyAsync方法用于创建一个异步任务,并返回一个CompletableFuture对象。该方法接受一个Supplier函数式接口作为参数,表示要执行的任务。

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    // 模拟耗时操作
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return "Hello, CompletableFuture!";
});

2.2 使用runAsync创建

runAsync方法用于创建一个没有返回值的异步任务。该方法接受一个Runnable函数式接口作为参数。

CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
    // 模拟耗时操作
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("Task completed!");
});

3. 处理任务结果

3.1 thenApply方法

thenApply方法用于在任务完成后对结果进行处理,并返回一个新的CompletableFuture对象。

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello")
    .thenApply(result -> result + " World");

future.thenAccept(System.out::println);  // 输出: Hello World

3.2 thenAccept方法

thenAccept方法用于在任务完成后消费结果,但不返回新的结果。

CompletableFuture.supplyAsync(() -> "Hello")
    .thenAccept(result -> System.out.println(result + " World"));  // 输出: Hello World

3.3 thenRun方法

thenRun方法用于在任务完成后执行一个无参数的操作。

CompletableFuture.supplyAsync(() -> "Hello")
    .thenRun(() -> System.out.println("Task completed!"));  // 输出: Task completed!

4. 异常处理

4.1 exceptionally方法

exceptionally方法用于处理任务执行过程中可能出现的异常,并返回一个默认值。

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    if (true) {
        throw new RuntimeException("Error occurred!");
    }
    return "Hello";
}).exceptionally(ex -> {
    System.out.println("Exception: " + ex.getMessage());
    return "Default Value";
});

future.thenAccept(System.out::println);  // 输出: Default Value

4.2 handle方法

handle方法用于处理任务的结果或异常,并返回一个新的结果。

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    if (true) {
        throw new RuntimeException("Error occurred!");
    }
    return "Hello";
}).handle((result, ex) -> {
    if (ex != null) {
        System.out.println("Exception: " + ex.getMessage());
        return "Default Value";
    }
    return result;
});

future.thenAccept(System.out::println);  // 输出: Default Value

5. 组合多个CompletableFuture

5.1 thenCompose方法

thenCompose方法用于将两个CompletableFuture串联起来,前一个任务的结果作为后一个任务的输入。

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello")
    .thenCompose(result -> CompletableFuture.supplyAsync(() -> result + " World"));

future.thenAccept(System.out::println);  // 输出: Hello World

5.2 thenCombine方法

thenCombine方法用于将两个CompletableFuture的结果进行合并。

CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> " World");

CompletableFuture<String> combinedFuture = future1.thenCombine(future2, (result1, result2) -> result1 + result2);

combinedFuture.thenAccept(System.out::println);  // 输出: Hello World

5.3 allOf方法

allOf方法用于等待多个CompletableFuture全部完成。

CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> " World");

CompletableFuture<Void> allFutures = CompletableFuture.allOf(future1, future2);

allFutures.thenRun(() -> {
    System.out.println("All tasks completed!");
    System.out.println(future1.join() + future2.join());  // 输出: Hello World
});

5.4 anyOf方法

anyOf方法用于等待多个CompletableFuture中的任意一个完成。

CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return "Hello";
});

CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> " World");

CompletableFuture<Object> anyFuture = CompletableFuture.anyOf(future1, future2);

anyFuture.thenAccept(result -> System.out.println("First completed: " + result));  // 输出: First completed: World

6. 总结

CompletableFuture是Java 8中引入的一个强大的并发工具,它提供了丰富的API来处理异步任务的结果、异常以及任务之间的组合。通过CompletableFuture,开发者可以更加简洁、高效地编写并发程序。掌握CompletableFuture的使用方法,对于提升Java并发编程能力具有重要意义。

推荐阅读:
  1. Java8中CompletableFuture的使用方法
  2. 怎么使用Java8新特性Effectively final

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java completablefuture

上一篇:SpringBoot项目如何使用hutool工具进行http接口调用

下一篇:Spring的@Transactional怎么使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》