我正在使用一个数据相关的 API 接口,它有一个关键的void回调函数,该函数会自动调用来标记某些 IO 操作的结束。我想创建类Callable<String>
并使用Future<String> result
。
我苦苦思索如何让 Callable 返回字符串。String returnResult(){return this.result}
在内部创建一个函数来调用不行。
请指教。
它看起来像:
public class MyCallable implements someAPIWrapper, Callable<String> {
String result;
@Override
public void endOfJobCallback() { //predefined API callback marking end of work
/*
usually read the data and write to a file, but not my case.
how to return this.result string from here?
*/
}
@Override
public String call() throws Exception {
//some logic stuff
//make API call to request a bunch of data
//inside a loop to listen to incoming messages, receiving and appending to the *result* variable
//end of all messages signalled by the ending callback, stop loop and return result var
}
}
class Main {
public static void main(String[] args){
MyCallable callable = new MyCallable();
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<String> future = executor.submit(callable);
String result = future.get(); //blocking until result ready
}
}
您可以使用(原子)布尔值来知道何时停止循环:
注意:由于您没有添加任何代码,因此不清楚您究竟是如何收听消息的。您可能希望采纳该想法并将其改编为实际代码,具体取决于您是否进行简短轮询、是否拥有 webhook 等
CompletableFuture
您可以通过在 中添加 来使其工作MyCallable
,然后在 中完成它endOfJobCallback()
。然后在你的
main()
:(当然这需要确保
endOfJobCallback()
在 100% 的情况下被调用,否则您可能需要实现一些错误处理,或者您可能想要使用get(timeout, unit)
而不是join()
)