【发布时间】:2017-09-11 13:21:12
【问题描述】:
所以,场景是这样的:
//Some code...
public Map<String, String> someFunction() {
for (final UserDetail user : userDetailList) {
// the following (below) code runs in background thread
// long running task
new RecordPersonalisedDao().getPendingRecordsForUid(user.getuId(), new RecordPersonalisedDao.OnResultFetched() {
@Override
public void onResult(Result result) {
// callback after the user is processed
// put some parameter from result to map
map.put(user.getName(), result.getTotal());
}
});
}
// return map only after all users are processed
return map;
}
正如上面这段代码的注释中提到的,我希望只有在处理完整个用户列表后才返回最终的地图。
我无法更改RecordPersonalisedDao#getPendingRecordsForUid 的功能,使其仅在主线程中运行。
如何在 java 中实现这一点?
编辑:这种类型的问题通常会遇到。所以,我想了解java中相同的解决方案。
简单地说,我想要这样的行为
- 在后台为数组中的所有成员运行此代码,完成后,发送回调。
(大概)
[list_of_some_data]
.forEach( run this function )
.after(after the function is run in background for all members of list - return some value)
【问题讨论】:
-
使用join()方法等待后台线程完成。
-
你想要的是一个 ExecutorService 并使用提交任务返回的 Future 作为你的回调。
-
如果我理解正确,那么您想使用
Future并使用CompletableFuture.allOf以等待所有Futures。见这里stackoverflow.com/a/36261808/3883957。
标签: java multithreading java-threads