ManbaBryant 2023-04-08 15:40 采纳率: 0%
浏览 9

关于CompletableFuture的疑惑

当我使用CompletableFuture的默认线程池时,只输出:main线程结束了,为什么不输出:最终结果为=

public class Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "hello";
        }).whenComplete((v, e) -> {
            if (e == null) {
                System.out.println("最终结果为=" + v);
            }
        }).exceptionally(e -> {
            System.out.println("出现异常=" + e);
            return null;
        });
        System.out.println("main线程结束了");
    }
}
  • 写回答

2条回答 默认 最新

  • 阿里嘎多学长 2023-04-08 18:00
    关注

    以下内容部分参考ChatGPT模型:


    这是因为主线程在启动CompletableFuture后就立刻结束了,而CompletableFuture是在另一个线程中执行的,所以主线程并不会等到CompletableFuture执行完毕再退出。如果想要让主线程等待CompletableFuture执行完毕后再退出,可以使用CompletableFuture的join方法。

    例如:

    public class Test {
        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";
            }).whenComplete((v, e) -> {
                if (e == null) {
                    System.out.println("最终结果为=" + v);
                }
            }).exceptionally(e -> {
                System.out.println("出现异常=" + e);
                return null;
            });
    
            System.out.println("main线程结束了");
    
            future.join(); // 等待CompletableFuture执行完毕
        }
    }
    

    如果我的建议对您有帮助、请点击采纳、祝您生活愉快

    评论

报告相同问题?

问题事件

  • 创建了问题 4月8日

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程