首页 > 编程语言 >Java中的异步编程与CompletableFuture应用

Java中的异步编程与CompletableFuture应用

时间:2024-07-20 15:54:47浏览次数:8  
标签:异步 Java util concurrent CompletableFuture import java public

Java中的异步编程与CompletableFuture应用

大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!

在现代 Java 编程中,异步编程变得越来越重要,它可以帮助我们提高应用程序的响应速度和性能。CompletableFuture 是 Java 8 引入的一个强大工具,它简化了异步编程,使得编写非阻塞代码变得更加容易。本文将详细介绍 CompletableFuture 的基本用法及其在实际开发中的应用。

1. 引入 CompletableFuture

CompletableFuturejava.util.concurrent 包的一部分,提供了在完成计算后可以操作的 Future 版本。它支持异步编程、链式调用、组合多个异步操作等功能。首先,我们需要在项目中确保使用 Java 8 或更高版本。

2. 创建 CompletableFuture

可以通过静态方法 CompletableFuture.supplyAsync() 创建一个异步任务。以下是一个基本的示例:

package cn.juwatech.completablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class BasicUsage {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000); // 模拟长时间运行的任务
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Hello, CompletableFuture!";
        });

        // 阻塞直到计算完成并获得结果
        String result = future.get();
        System.out.println("Result: " + result);
    }
}

3. 链式调用

CompletableFuture 支持链式调用,可以在一个任务完成后继续执行其他任务。例如:

package cn.juwatech.completablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class Chaining {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture.supplyAsync(() -> {
            return "Hello";
        }).thenApply(result -> {
            return result + ", World";
        }).thenAccept(System.out::println);
    }
}

在这个例子中,thenApply() 方法接收前一个阶段的结果,并返回一个新的结果。thenAccept() 方法用来处理最终结果,但不返回任何值。

4. 异常处理

CompletableFuture 提供了异常处理的方法,例如 exceptionally(),用于处理计算过程中出现的异常:

package cn.juwatech.completablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class ExceptionHandling {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            if (true) { // 模拟异常情况
                throw new RuntimeException("Something went wrong!");
            }
            return 1;
        }).exceptionally(ex -> {
            System.out.println("Exception: " + ex.getMessage());
            return 0;
        });

        // 获取结果
        Integer result = future.get();
        System.out.println("Result: " + result);
    }
}

5. 组合多个 CompletableFuture

可以使用 thenCombine()thenCompose() 方法来组合多个异步任务:

  • thenCombine() 用于将两个独立的 CompletableFuture 结果结合起来。
package cn.juwatech.completablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CombiningFutures {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 2);
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 3);

        CompletableFuture<Integer> combinedFuture = future1.thenCombine(future2, (result1, result2) -> result1 + result2);
        Integer combinedResult = combinedFuture.get();
        System.out.println("Combined Result: " + combinedResult);
    }
}
  • thenCompose() 用于链式调用,处理一个异步任务的结果并返回另一个 CompletableFuture
package cn.juwatech.completablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class ComposingFutures {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 2)
                .thenCompose(result -> CompletableFuture.supplyAsync(() -> result * 2));

        Integer finalResult = future.get();
        System.out.println("Final Result: " + finalResult);
    }
}

6. 并行执行多个 CompletableFuture

使用 allOf()anyOf() 方法可以并行执行多个异步任务:

  • allOf() 等待所有 CompletableFuture 完成:
package cn.juwatech.completablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class AllOfExample {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            System.out.println("Task 1");
        });
        CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
            System.out.println("Task 2");
        });

        CompletableFuture<Void> allOfFuture = CompletableFuture.allOf(future1, future2);
        allOfFuture.get(); // 等待所有任务完成
        System.out.println("All tasks completed");
    }
}
  • anyOf() 等待任意一个 CompletableFuture 完成:
package cn.juwatech.completablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class AnyOfExample {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Task 1 completed";
        });
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            return "Task 2 completed";
        });

        CompletableFuture<Object> anyOfFuture = CompletableFuture.anyOf(future1, future2);
        String result = (String) anyOfFuture.get();
        System.out.println(result);
    }
}

7. 总结

CompletableFuture 是处理异步编程的强大工具,它不仅简化了异步任务的处理,还支持丰富的功能,如异常处理、任务组合和并行执行等。通过掌握这些技术,可以使得你的 Java 应用程序在处理异步任务时更加高效和灵活。

本文著作权归聚娃科技微赚淘客系统开发者团队,转载请注明出处!

标签:异步,Java,util,concurrent,CompletableFuture,import,java,public
From: https://www.cnblogs.com/szk123456/p/18313206

相关文章

  • 使用Java和Google Guava简化开发
    使用Java和GoogleGuava简化开发大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!GoogleGuava是Google开发的一个Java开源库,它提供了许多工具和库来简化Java开发。Guava提供了从集合类到缓存、字符串处理、并发工具等多种功能。本篇文章将介绍如......
  • 使用Java和Spring MVC构建Web应用
    使用Java和SpringMVC构建Web应用大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!在现代企业中,Web应用程序是最常见的应用类型之一。SpringMVC是一个强大且流行的JavaWeb框架,用于构建功能强大且易于维护的Web应用程序。本文将通过实际示例展示如......
  • 使用 useLazyFetch 进行异步数据获取
    title:使用useLazyFetch进行异步数据获取date:2024/7/20updated:2024/7/20author:cmdragonexcerpt:摘要:“使用useLazyFetch进行异步数据获取”介绍了在Nuxt开发中利用useLazyFetch进行异步数据加载的方法,强调其立即触发导航特性,与useFetch相似的使用方式,以及如何......
  • Java中的编译器插件开发与应用
    Java中的编译器插件开发与应用大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!在Java语言中,编译器插件的开发与应用是一种高级编程技术,能够扩展Java编译器的功能,以满足特定的需求。这些插件可以在编译过程中进行代码分析、优化,甚至修改源代码。本文将......
  • 使用Java和Elastic Stack进行日志分析
    使用Java和ElasticStack进行日志分析大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!在现代企业中,日志分析是确保系统健康、进行故障排查和优化性能的重要环节。ElasticStack(ELKStack)是一个强大的工具集,包含Elasticsearch、Logstash和Kibana,能够有......
  • 一周学完Java基础,第六天,常见容器
    (1)列表List         接口:    java.util.List<>    实现方式:    java.util.ArrayList<>:变长数组    java.util.LinkedList<>:双链表    函数:    add():在末尾添加一个元素    clear():......
  • 学生Java学习路程-3
    ok,到了一周一次的总结时刻,我大致会有下面几个方面的论述:1.这周学习了Java的那些东西2.这周遇到了什么苦难3.未来是否需要改进方法等几个方面阐述我的学习路程。这周首先就是进行了for循环跟while的一些练习,主要学习的方面在Scanner的学习,这是网上以及网课建议新手用的输入形式,以......
  • JavaScript Program to print pyramid pattern (打印金字塔图案的程序)
     编写程序打印由星星组成的金字塔图案 例子: 输入:n=6输出:    *    **    ***    ****    *****    ******     *****    ****    ***    **    ......
  • Javascript 在我的本地服务器上运行,但在 WordPress 上不起作用
    大家好,我有一个问题。我有一个在本地服务器中完美运行的模板/主题,但是当我将其移动到Wordpress时,根据我的研究,我得到了“jQuery不兼容”的信息。 我附上了代码的图像。你能帮我一下吗,一切看起来都很完美,在我看来一切都很完美,但在Wordpress中却不然。提前谢谢你!......
  • Java基础语法(一)
    目录一、Java入门 java定义前期准备Java应用java的主要特性JDK和JRE二、Java基础概念注释关键字关键字特点字面量分类特殊的字面量\t变量数据类型标识符键盘录入Scanner类三、运算符四、循环和判断五、数组六、方法一、Java入门 java定义  ......