首页 > 解决方案 > 尝试在 java 中使用 CompletableFuture 类时,未返回输出,我搞砸了什么?

问题描述

Java 和 CompletableFuture 类的新手。我的程序运行,但没有向控制台返回任何内容。确信它的变量没有被打印或分配到某处,但无法弄清楚。我究竟做错了什么?

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.concurrent.CompletableFuture;


public class AsyncMain {

    public String contents;

    public void process(String output) throws IOException {

        URL address = new URL("https://api.publicapis.org/random?category=animal");

        InputStreamReader reader = null;
        try {
            reader = new InputStreamReader(address.openStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        BufferedReader buffer = new BufferedReader(reader);

        //String contents = "";
        String line = "";

        while((line = buffer.readLine()) != null){
            if (line.isEmpty()) {
                break;
            }
            contents += line;
        }

        output = contents;
        System.out.println(output.toString());
    }

    public String address_3(String msg){
        try {
            this.process(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(msg);
        return msg;

    }

    public String address_2(String msg){
        try {
            this.process(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(msg);
        return msg;
    }

    public String address_1() {
        try {
            this.process(null);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static void main(String args[]){
        AsyncMain as = new AsyncMain();
        CompletableFuture<String> cf = new CompletableFuture<>();

        cf.supplyAsync(as::address_1)
            .thenApply(as::address_2)
            .thenApply(as::address_3);
    }
}

我在这里尝试了独立于 CompletableFuture 尝试的“进程”功能。它工作并从 URL 对象返回一个字符串值。但是当尝试与 CompletableFuture 类集成以从 URL 对象中打印出 2 个值时。没有任何东西被打印到控制台。

标签: java

解决方案


这行代码返回一个CompletableFuture.

CompletableFuture<String> completableFuture =
        cf.supplyAsync(as::address_1).thenApply(as::address_2).thenApply(as::address_3);

在您的情况下,主线程在CompletableFuture. 如果你用睡眠阻塞主线程,你可以看到结果。

cf.supplyAsync(as::address_1).thenApply(as::address_2).thenApply(as::address_3);
Thread.sleep(5000);

CompletableFuture定义可以与其他步骤组合的异步计算步骤的合同。你也可以CompletableFuture<String>通过CompletableFuture.get()方法调用得到结果,这也会阻塞主线程,直到Future步骤完成。

CompletableFuture<String> completableFuture =
        cf.supplyAsync(as::address_1).thenApply(as::address_2).thenApply(as::address_3);
completableFuture.get();


推荐阅读