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);
        }
    }
}
相关推荐
Flittly8 小时前
【AgentScope Java新手村系列】(16)从RAG到多路检索
java·spring boot·spring
小兔崽子去哪了9 小时前
Java 生成二维码解决方案
java·后端
人活一口气13 小时前
从JVM调优到MCP协议:Java全栈技术体系深度总结与企业级架构实践
java·spring boot
NE_STOP15 小时前
Vibe Coding -- 完整项目案例实操
java
荣码15 小时前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
SimonKing15 小时前
Google第三方授权登录
java·后端·程序员
明月光81815 小时前
从一行 @Builder 说起:重新拾起 Java 的 Lombok、注解与 Builder 模式
java
考虑考虑1 天前
Mybatis实现批量插入
java·后端·mybatis
咖啡八杯1 天前
GoF设计模式——中介者模式
java·后端·spring·设计模式
青石路1 天前
记一次多JDK版本问题的排查,一坑套一坑,差点没爬上来
java