我有一种情况,我必须停止主线程,直到执行第二个线程为止。
@Test
@UiThreadTest
public void shouldShowClipboardViewOnCopyText() {
...
}
答案 0 :(得分:0)
您可以将计算结果包装在CompletableFuture中,然后等待将来完成。我已根据您的代码在下面放置了示例,您可能需要进行一些更改才能使它起作用,但是您将获得大致的想法
@PostMapping("/filter")
public ResponseEntity<?> filter(@Valid @RequestBody R1 r1) throws InterruptedException {
Double lat = (r1.getLat());
Double lang = r1.getLongi();
List<LatLang> list2 =latlangRepo.findAllWithin(lang,lat);
List<Future<String>> futures = new ArrayList<>();
for (i = 0; i < x; i++) {
Double lat1 = list2.get(i).getLat();
Double longi1 = list2.get(i).getLang();
//Delegate to the thread asynchronously
Future<String> completableFuture = calculateAsync();
futures.add(completableFuture);
}
//Wait for the completion of all the futures and collact result
String combined = futures.stream().
.map(CompletableFuture::join)
.collect(Collectors.joining(" "));
}
public Future<String> calculateAsync(Double lat, Double long) throws InterruptedException {
CompletableFuture<String> completableFuture
= new CompletableFuture<>();
Executors.newCachedThreadPool().submit(() -> {
//Your computation here
completableFuture.complete("Result of your computation");
});
return completableFuture;
}
查看更多示例here