CompletableFuture 开启异步线程,主线程不等待

在Java中CompletableFuture用于异步编程,异步编程是编写非阻塞的代码,运行的任务在一个单独的线程,与主线程隔离,并且会通知主线程它的进度,成功或者失败。

在这种方式中,主线程不会被阻塞,不需要一直等到子线程完成。主线程可以并行的执行其他任务。

使用这种并行方式,可以极大的提高程序的性能。

一般应用场景:在业务开发中可能会遇到调用多个第三方接口,同时要求主流程不被阻塞。

复制代码
    public static void main(String[] args) throws Exception {
        // 开启一个线程(无返回值)
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        // 开启一个线程(有返回值)
        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3);
                return 1;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        {
            // do things
        }
        // 等待异步现成执行完
        CompletableFuture.allOf(integerCompletableFuture).get();
        // 等待多个异步现成执行完
        CompletableFuture.allOf(voidCompletableFuture,integerCompletableFuture).get();
        // 打印异步结果
        System.out.println(integerCompletableFuture.get());
        System.out.println("over");
    }
相关推荐
坚持就完事了4 分钟前
Java中的异常
java·开发语言
MoonPointer-Byte7 分钟前
【Python实战】我开发了一款“诗意”待办软件:MoonTask(附源码+工程化思路)
开发语言·python·custom tkinter
~央千澈~7 分钟前
抖音弹幕游戏开发之第11集:礼物触发功能·优雅草云桧·卓伊凡
java·前端·python
wuqingshun31415916 分钟前
说一下HashMap和HashTable的区别
java·开发语言
沐知全栈开发24 分钟前
Bootstrap 多媒体对象
开发语言
PythonFun28 分钟前
WPS动态序号填充,告别手动调整烦恼
java·前端·python
Hx_Ma1629 分钟前
测试题(二)
java·开发语言
ShineWinsu30 分钟前
对于C++中list的详细介绍
开发语言·数据结构·c++·算法·面试·stl·list
tackchen30 分钟前
venv-manager 管理 Conda 环境 和 Python 虚拟环境 (venv)
开发语言·python·conda
lly20240639 分钟前
ASP #include 指令详解
开发语言