Java 实现异步转同步的方法

相信大家在项目开发过程中会遇到需要将异步操作转换为同步操作的情况,下面给大家介绍 CompletableFuture 的用法

java 复制代码
package future;

import java.util.Locale;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class Main {

    public static void costTimeOperation(int a, int b, final Callback callback) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(2000);
                    callback.onComplete(a+b);
                } catch (Exception e) {
                    System.out.println(e);
                    callback.onError(e);
                }
            }
        };
        thread.start();
    }

    interface Callback {
        void onComplete(int result);
        void onError(Exception e);
    }


    public static void main(String[] args) {
        CompletableFuture<Integer> future = new CompletableFuture<>();
        int a = 1;
        int b = 2;
        costTimeOperation(a, b, new Callback() {
            @Override
            public void onComplete(int result) {
                future.complete(result);
            }

            @Override
            public void onError(Exception e) {
                future.complete(null);
            }
        });
        try {
            System.out.printf(Locale.getDefault(), "Waiting for result of %d+%d...%n", a,b);
            System.out.println(future.get(5000, TimeUnit.MILLISECONDS));
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
相关推荐
这周也會开心1 天前
SpringMVC整理
java·springmvc
東雪木1 天前
Spring Boot 2.x 集成 Knife4j (OpenAPI 3) 完整操作指南
java·spring boot·后端·swagger·knife4j·java异常处理
数学难1 天前
Java面试题2:Java线程池原理
java·开发语言
Charles_go1 天前
C#8、有哪些访问修饰符
java·前端·c#
qwer12321ck761 天前
srcType instanceof Class 及泛型 vs 普通类
java
咸鱼求放生1 天前
Java 8 Stream API
java·开发语言
moiumxf0278q1 天前
C++中智能指针是如何工作的?
java·jvm·c++
尼古拉斯·纯情暖男·天真·阿玮1 天前
泛型与数据结构
java·数据结构
半旧夜夏1 天前
【Gateway】服务调用和网关配置攻略
java·spring boot·spring cloud·gateway