我正在使用一个与数据相关的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
}
}
您可以使用(原子)布尔值来知道何时停止循环:
public class MyCallable implements someAPIWrapper, Callable<String> {
String result;
private final AtomicBoolean complete = new AtomicBoolean();
@Override
public void endOfJobCallback() { //predefined API callback marking end of work
complete.set(true); //set Boolean to true atomically
}
@Override
public String call() throws Exception {
while (!complete.get()) {
//Do your stuff
}
//if you reach this the callback was called
return result;
}
}