gpt4 book ai didi

Java异步调用方法等待返回

转载 作者:行者123 更新时间:2023-12-02 03:34:15 25 4
gpt4 key购买 nike

我知道可能有几种方法可以做到这一点,只是寻找最有效和最简洁的方法:

public Object giveMeNewObject() {
final Object result = null;
SomeApiClient.start(new Callback() { // starts an async process
@Override
public void onSuccess(Object somethingNew) {
result = somethingNew; //ERROR; can't set cause final
}
});
return result; //result is null, cause Async already finished
}

最佳答案

从您的代码中 - 这是动态修改的,因此纠正错误,一切都会按您的预期工作 - 调用者将等到第 3 方完成处理并获得该过程的结果:

public Object giveMeNewObject() {
CountDownLatch latch=new CountDownLatch(1);
Callback callback=new Callback() {
public sometype result=null;
@Override
public void onSuccess(Object somethingNew) {
result = somethingNew; //ERROR; can't set cause final
latch.countDown();
}
});
SomeApiClient.start(callback);
latch.await(sometimetowait);
return callback.result;

}

关于Java异步调用方法等待返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37631422/

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