我正在尝试使用线程进行并行调用。为此,我使用Callable接口,因为我需要一个参数。问题是我在一个循环中用参数使线程成为线程,并且传递的值总是被覆盖,因此当它到达 call()方法时,它总是具有最后一个传递的值。
private HotelResponseDto getHotelsCall(HotelRequest request) {
Set<Suggestion> suggestions = repository.findByHistoryId(request.getId());
List<Callable<HotelWrapperDto>> calls = new ArrayList<>();
ExecutorService executor = new ScheduledThreadPoolExecutor(suggestions.size());
for (Suggestion s : suggestions) {
request.setCityCode(s.getName());
calls.add(new MyCallable(request)); //beginning of the issue
}
List<Future<HotelWrapperDto>> results = null;
try {
results = executor.invokeAll(calls);
} catch (InterruptedException e) {
e.printStackTrace();
}
List<HotelWrapperDto> wrappers = new ArrayList<>();
for (Future<HotelWrapperDto> f : Objects.requireNonNull(results)) {
try {
wrappers.add(f.get());
} catch (InterruptedException | ExecutionException e) {
log.error("Something didn't work.");
}
}
HotelResponseDto response = new HotelResponseDto();
response.setWrappers(wrappers);
return response;
}
这是MyCallable类
class MyCallable implements Callable<HotelWrapperDto> {
private HotelRequest hotel;
MyCallable(HotelRequest request) {
hotel = request;
//Here is the problem
//Because I call this constructor in a loop,
//hotel variable is always overwritten and in the end
//I get the last result for every iteration
}
@Override
public HotelWrapperDto call() {
HotelRequest hotelRequest = helper.createHotelRequest(hotel);
HotelWrapperDto wrapper = hotelService.getHotels(hotelRequest);
return wrapper;
}
}
我曾骑过其他有关带有参数的线程的文章,但没有找到任何解决方案。 如何找到适合我的情况的解决方案? (我稍后会清理代码)