java - 尝试在 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 个值时。没有任何东西被打印到控制台。
解决方案
这行代码返回一个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();
推荐阅读
- ios - iOS:根据条件覆盖滑动手势
- javascript - 是否可以使用对象结构来访问函数,以便代码完成更容易找到正确的函数
- asp.net - ASP.NET Web 窗体中的 Paypal IPN 事件侦听器未正确处理请求
- python - 使用 Python 3“请求”的 Artifactory AQL 查询
- html - 如何使用 Bootstrap 5 实现这种布局?
- amazon-web-services - Terraform AWS 未访问 localstack
- sql - 在 Oracle Sql 开发人员中将数据分离到不同的列中
- beyondcompare - 将 Beyond Compare 与远程 linux 服务器一起使用——在单个会话中打开变更集
- python - Airflow 中的延迟通知系统
- typescript - TypeScript - 获取所有祖先 - Type (...) 缺少 type (...) pop、push、concat、join 和另外 24 个属性中的以下属性