gpt4 book ai didi

java - 可通过 while 循环调用

转载 作者:行者123 更新时间:2023-11-29 08:36:17 25 4
gpt4 key购买 nike

我需要提供代码,使用 ExecutorService、Callable 和 Future 将进行一些计算并打印部分结果,直到达到定义的条件。我首先想到的是使用 while 循环。不幸的是,据我了解 ExecutorService.get() 会等到任务完成,所以我不能做类似(伪代码)的事情:

public Object call() throws Exception {
try {
while(!condition) {
//perform calc
return partialCalculationResult;
}
}
catch(InterruptedException e){
}
}

谁能指导我正确的方向是什么?

最佳答案

这里是:

while(!condition) {
//perform calc
return partialCalculationResult;
}

表示您的逻辑中存在“漏洞”。这可能应该是这样的:

while(!condition) {
// perform computation
push intermediate results somewhere
}
return finalResult;

换句话说:您在这里谈论的是两个不同的元素。对于那些“进度”更新,您将需要某种共享数据结构;例如一个队列

你看,与其他语言不同的是,没有内置的“生成器”概念可以让你从循环中产生值;就像你可以在 python 中做的那样或 scala例如。

关于java - 可通过 while 循环调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43912892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com