前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >还在用Future搞异步?快看看企业中常用的CompletableFuture是怎么用的!

还在用Future搞异步?快看看企业中常用的CompletableFuture是怎么用的!

作者头像
程序员牛肉
发布于 2024-11-21 11:47:40
发布于 2024-11-21 11:47:40
13100
代码可运行
举报
运行总次数:0
代码可运行

大家好,我是程序员牛肉。

不知道你们在使用多线程的时候会用什么方式来获取异步结果?大多数人接触的首个方法肯定是使用Future来获取异步结果。

让我们先看一下一整个Future的结构图

[Future 是 Java 并发包(java.util.concurrent)中的一个接口,用于表示一个异步计算的结果。它提供了一种机制,可以在异步任务完成后获取结果或处理异常。]

使用Future的方法很简单,如下图所示:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
 List<Future<Void>> futures = new ArrayList<>();
    for (OrderDTO order : ListResponse.getOrders(){
          futures.add(threadPool.submit(() -> {
           itemList.add(order);
            return null;}));
    }

这样的话,我们就可以获取所有执行任务线程的Future对象,通过这个对象,我们可以对执行任务的线程进行一些操作:

  1. 获取任务结果:
    • 使用 get() 方法可以获取任务的执行结果。如果任务尚未完成,get() 会阻塞当前线程,直到任务完成并返回结果。
    • get(long timeout, TimeUnit unit) 方法允许设置超时时间,如果在指定时间内任务未完成,则会抛出 TimeoutException。
  2. 取消任务:
    • 使用 cancel(boolean mayInterruptIfRunning) 方法尝试取消任务。参数 mayInterruptIfRunning 表示是否允许中断正在执行的任务。
    • 任务能否被取消取决于任务的状态以及是否支持取消操作。
  3. 检查任务状态:
    • isDone() 方法用于检查任务是否已经完成。
    • isCancelled() 方法用于检查任务是否在完成前被取消。

虽然基于Future我们对线程有了更加高的操作自由,但它也有自己的缺点。

1.Future接口中没有关于异常处理的方法,这对于我们的项目开发来讲是一个很憋屈的点。使用Future的时候需要我们在任务执行时捕获异常,然后将异常封装到 Future 对象中返回。

2.Future的不支持组合多个异步任务的结果,如果要处理多个异步任务之间的依赖或者组合,需要我们手动完成。

这么明显的缺点我们都能发现,那么更不要提那些维护Java的核心开发者了。

于是Java8狠活来袭,Java核心开发者引入了Completablefuture来解决我们上述提到的这两个问题。

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html 对应的官方文档

而我们这一篇主要介绍一下Completablefuture类中的常用方法。

1.runAsync: 执行异步计算,但是不会返回结果。该方法接受一个Runnable对象并且返回一个CompletableFuture<Void>。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
  CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
     try {
          System.out.println("Task is running in a separate thread: " + Thread.currentThread().getName());
          Thread.sleep(2000); // 模拟耗时操作
       } catch (InterruptedException e) {
                throw new IllegalStateException(e);
      }
            System.out.println("Task completed!");
        });    

2.supplyAsync: 执行异步计算,并返回结果。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
       CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            // 任务内容:模拟长时间运行的任务
            try {
                System.out.println("Task is running in a separate thread: " + Thread.currentThread().getName());
                Thread.sleep(2000); // 模拟耗时操作
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
            return "Task completed!";
        });

3.thenApply :thenApply 方法用于在 CompletableFuture 完成后,对其结果进行转换或处理,并返回一个新的 CompletableFuture。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public <U> CompletableFuture<U> thenApply(Function<? super T, ? extends U> fn)

代码实例:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public class CompletableFutureThenApplyExample {
    public static void main(String[] args) {
        // 创建一个异步任务,返回一个整数
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("Calculating... in thread: " + Thread.currentThread().getName());
            return 42; // 模拟一个计算结果
        });

        // 使用 thenApply 对结果进行转换,将整数转换为字符串
        CompletableFuture<String> stringFuture = future.thenApply(result -> {
            System.out.println("Transforming result in thread: " + Thread.currentThread().getName());
            return "The answer is " + (result+1);
        });
        }
    }
}

基于thenApply,我们实现了对CompletableFuture的结果进行的二次处理。需要注意的是thenApply在执行的时候,使用的是执行CompletableFuture的线程。

既然有这种两个任务是同一个线程处理的,那就有两个任务不是同一个线程处理的方法,它的名字叫做thenApplyAsync。

对比thenApplyAsync和thenApply的源码,会发现thenApplyAsync只不过是在提交参数的时候多提交了一个线程池。

4.thenAccept thenAccept 方法用于在 CompletableFuture 完成后,对其结果进行转换或处理。这个方法只消费,没有返回值。

代码例子就不举了,有点水字数的嫌疑了,参考看一下thenApply的代码就好了。

同理thenAccept在处理时使用的也是执行CompletableFuture的线程。而如果想要新开一个线程来处理thenAccept方法的话,可以使thenApplyAsync。

5.CompletableFuture.allOf() : 他是一个静态方法,用于组合多个方法,当所有的Completablefuture方法都完成的时候,返回的 CompletableFuture<Void> 也将完成。这在需要等待多个并发任务全部完成时非常有用。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    public static void main(String[] args) {
        CompletableFuture<Void> allOfFutures = CompletableFuture.allOf(future1, future2);
        allOfFutures.thenRun(() -> System.out.println("All tasks completed"));
    }

6.CompletableFuture.anyOf:等待任意一个给定的 CompletableFuture 完成。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    public static void main(String[] args) {
        CompletableFuture<Object> anyOfFutures = CompletableFuture.anyOf(future1, future2);
        anyOfFutures.thenAccept(result -> System.out.println("First completed task result: " + result));
    }

除此之外还有CompletableFuture还有一些方法没有被介绍,但这些内容一问GPT就知道了,没必要在这里赘述。

今天关于CompletableFuture的介绍就到这里了,本篇也主要是向大家介绍这么一个异步工具类去使用,不涉及底层原理。希望我的文章可以帮到你。

对于CompletableFuture你有什么想说的嘛?欢迎在评论区留言。

关注我,带你了解更多计算机干货。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2024-11-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序员牛肉 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
Assessing Biometric Authentication -A Holistic Approach
Biometric authentication is certainly starting to get the attention of the general public. Announcements like the revelation this past fall that over 1 billion stolen passwords had been amassed by a Russian crime ring underscore the fact that the current security systems are flawed, and that new approaches to security are necessary. There is a growing consensus in government and industry (and often confirmed in Hollywood) that biometric approaches are the best path forward. The push by Apple and Samsung to make fingerprint authentication available in their devices is among the most visible applications of biometrics.
用户6026865
2022/09/02
3090
Assessing Biometric Authentication -A Holistic Approach
Voice ID On-device - Embedded Secure Authentication Solution
Easy, Embedded and Secure Voice Biometric Authentication for Devices and Applications
用户6026865
2022/09/02
5100
Voice ID On-device - Embedded Secure  Authentication Solution
访谈 - Sensory CEO Todd Mozer与FindBiometrics CEO Peter O'Neil
Sensory CEO Todd Mozer近日接受了FindBiometrics CEO Peter O'Neil的专访。内容包括了 Sensory于2019年对Vocalize.ai,独立第三方语音和声音生物特征测试实验室的收购,以及包含语音识别和交互,面部识别和模拟的人的虚拟化身(virtual avatar)的应用,以及关于当但隐私保护的探讨等等。
用户6026865
2020/01/17
4330
Sensory TrulySecure - Easy, Embedded, Secure Authentication
Sensory TrulySecure Speaker Verification(TSSV)技术是独立于语言的(language independent),具备高度安全性和便利性的,设备端(on device)用户语音和短语(passphrase)验证技术。
用户6026865
2021/03/15
4650
Sensory TSSV - TrulySecureSpeakerVerificatio
TSSV-面向硬件设备和应用的嵌入式的和简单的安全验证(Secure Authentication)技术。
用户6026865
2020/08/17
6600
Sensory  TSSV - TrulySecureSpeakerVerificatio
SensoryCloud AI - 支持Liveness的声纹生物特征识别
Biometric data is the unique information that can be used to identify a person with accuracy. It includes uniquely identifiable features such as fingerprint, face recognition, iris, voice recognition. The increased acceptance of biometrics by consumers has encouraged the uptake of these systems on a wider scale.
用户6026865
2022/05/17
4430
专访 - Sensory CEO Todd Mozer - AI, 3D人脸识别以及其他
Sensory Inc.作为向全球移动设备提供先进的复杂生物识别算法的供应商,于近期展示了其采用面部和声音识别算法的AI虚拟银行助理技术。
用户6026865
2019/10/30
8130
专访 - Sensory CEO Todd Mozer - AI, 3D人脸识别以及其他
Sensory’s TrulyHandsfree and Arm’sCortex-M55
Efficient wake word recognition on microcontrollers with Cortex-M55 and Helium technology for use in consumer and automotive products that include more and more AI features for voice applications.
用户6026865
2022/09/02
3410
Sensory’s TrulyHandsfree and Arm’sCortex-M55
5 Predictions for Voice Technology in 2023
There is no doubt that voice is the most natural and convenient communication mode, so it's little wonder that the adoption of voice technology on smart devices has more recently become the preferred interface in many contexts.
用户6026865
2023/03/02
2970
5 Predictions for Voice Technology in 2023
Buy Now Pay Later, But At What Price? A Case for Face Biometrics
The speed at which we can buy and receive products has escalated with the rise of one click internet shopping, the gig economy for deliveries, and economies of scale through improved logistics, warehousing, and deliveries. The rise of robotic and drone deliveries is going to make it all the easier to get stuff fast. Helping the speed of buying is having our purchasing information stored on our computers and our phones. Buy Now Pay Later (BNPL) makes it all the faster because now we don’t even need to have the cash assets to buy things.
用户6026865
2022/05/17
2890
Buy Now Pay Later, But At What Price? A Case for Face Biometrics
DJI和GoPro运动相机语音控制对比和语音控制技术和创新应用的探讨
作为运动相机,必须要满足运动场景下的HANDS-FREE解放双手的操作,而语音则以用户最自然的方式,赋予用户直观,强大和自然的人机交互方式。
用户6026865
2020/09/29
1.7K0
DJI和GoPro运动相机语音控制对比和语音控制技术和创新应用的探讨
疫情期间戴口罩仍可识别的Sensory Biometric面部识别解决技术
Sensory TrulySecure人声和面部生物识别技术(face and voice biometrics)为用户带来极大的便利性,同时为用户在COVID-19新常态期间带来新价值 - 用户带口罩仍可正常识别,而且可以识别咳嗽和打喷嚏(cough and sneezes)。
用户6026865
2020/06/12
6930
疫情期间戴口罩仍可识别的Sensory Biometric面部识别解决技术
多模态PCANet:一种高精度、低复杂度的鲁棒3D活体检测方案
当下正值新冠肺炎(COVID-19)肆虐全球之际,戴口罩成为了全民阻断病毒传播的最佳方式。然而在人脸部分遮挡或恶劣光照条件下,用户人脸识别或人脸认证的合法访问常常提示活体检测失败,甚至根本检测不到人脸。这是由于目前基于RGB等2D空间的主流活体检测方案未考虑光照、遮挡等干扰因素对于检测的影响,而且存在计算量大的缺点。而数迹智能团队研发的3D SmartToF活体检测方案则可以有效解决此问题。那么什么是活体检测?什么又是3D活体检测?以及怎么实现恶劣环境(如人脸遮挡、恶劣光照等)与人脸多姿态变化(如侧脸、表情等)应用场景下的活体检测呢?本文将会围绕这些问题,介绍数迹智能的最新成果——基于ToF的3D活体检测算法。
3D视觉工坊
2020/11/11
1.5K0
多模态PCANet:一种高精度、低复杂度的鲁棒3D活体检测方案
Sensory生物识别技术 - 更安全,更便捷,最具成本优势
生物身份识别和验证技术讲究的是在易用性和识别准确性之间的平衡(conbination of convenience and accuracy)。
用户6026865
2020/12/14
5940
Sensory生物识别技术 - 更安全,更便捷,最具成本优势
Sensory&Philips-Enhance ASR with Speech Enhancement
Sensory, a Silicon Valley company enhancing user experience and security for consumer electronics, announced today its collaboration with Philips, a provider of advanced speech enhancement technologies, to offer a combined technology suite. This would package Sensory’s best-in-class speech recognition technologies TrulyHandsfree™ and TrulyNatural™ with Philips BeClear Speech Enhancement™ algorithms, resulting in significant accuracy improvement in noisy environments. By processing an audio signal with Philips’ echo cancellation, noise suppression and/or beam-forming processors before passing it to Sensory’s speech recognition engine, much of the unwanted ambient noise in a signal can be filtered out, leaving the critical speech portion of the signal largely untouched. This process allows Sensory’s already noise robust speech recognizer to decipher near- and far-field speech more accurately in conditions where very high ambient noise is present.
用户6026865
2022/09/02
5000
Sensory&Philips-Enhance ASR with Speech Enhancement
ST&Sensory&DSPC Joint Webiner
Customizable embedded voice recognition solutions without external connectivity
用户6026865
2023/03/02
3850
ST&Sensory&DSPC Joint Webiner
Introducing SensoryCloud.ai: Flexibility
After a quarter century of running embedded or “on the Edge” Sensory is moving into the cloud with the opportunity to offer hybrid solutions with more Flexibility, Accuracy, Features/Technologies, Privacy and Cost advantages than ever before.
用户6026865
2022/04/02
2170
Introducing SensoryCloud.ai:  Flexibility
CV学习笔记(二十八):活体检测总结②
和传统的方法结构类似,只是使用了VGG进行特征提取,通过CNN网络端到端学习anti-spoofing的表示空间
云时之间
2020/07/22
1.3K0
Anti-Spoofing之人脸活体检测
每周精选 Algorithm System Anti-Spoofing 之人脸活体检测 在小编之前的文章系列中曾介绍过的对抗样本攻击,是目前Deep Learning比较火热的一个研究方向,因为它掀起了关注深度学习在安全领域潜在问题的热潮。虽然活跃于学术界的对抗样本目前还未渗入到工业界中,anti-spoofing(反欺诈)仍一直是大家关注的焦点。人脸识别是大家最为熟悉的应用深度学习的例子,结合人脸识别技术的APP在市面上比比皆是,本文将简单介绍在人脸识别应用中的反欺诈技术——人脸活体检测。 人脸识别,
企鹅号小编
2018/01/29
5.3K0
重磅纯干货 | 超级赞的语音识别/语音合成经典论文的路线图(1982-2018.5)
网址:https://github.com/zzw922cn/awesome-speech-recognition-speech-synthesis-papers
用户7623498
2020/08/04
1.3K0
推荐阅读
相关推荐
Assessing Biometric Authentication -A Holistic Approach
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档