springboot 线程池并行化处理如何保证全部执行完获得结果 可以使用wait吗
时间: 2024-01-02 14:04:35 浏览: 46
不建议使用`wait()`方法来等待异步方法执行完毕并获取结果,因为`wait()`方法会让当前线程进入等待状态,如果异步方法在等待期间执行完毕并返回结果,也无法唤醒等待的线程,从而导致等待时间过长或者死锁等问题。
相比于`wait()`方法,`join()`方法更加适合等待异步方法执行完毕并获取结果,因为`join()`方法会让当前线程等待异步方法执行完毕,并在异步方法执行完毕后返回结果,并且不会阻塞线程。
如果需要等待多个异步方法执行完毕并获取结果,可以使用`CompletableFuture.allOf()`方法等待所有异步方法执行完毕,并使用`CompletableFuture.join()`方法获取所有异步方法的结果。
示例代码如下:
```java
// 1. 在需要并行化处理的方法上添加@Async注解
@Service
public class MyService {
@Async
public CompletableFuture<String> doSomethingAsync(int index) {
// 需要异步执行的方法
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return CompletableFuture.completedFuture("done-" + index);
}
}
// 2. 调用需要并行化处理的方法,并等待所有异步方法执行完毕
@RestController
public class MyController {
@Autowired
private MyService myService;
@GetMapping("/async")
public List<String> async() throws InterruptedException {
List<CompletableFuture<String>> futures = new ArrayList<>();
// 调用10次异步方法
for (int i = 0; i < 10; i++) {
futures.add(myService.doSomethingAsync(i));
}
// 等待所有异步方法执行完毕,并返回结果
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
return futures.stream().map(CompletableFuture::join).collect(Collectors.toList());
}
}
```
在上面的示例代码中,我们使用`CompletableFuture.allOf()`方法等待所有异步方法执行完毕,并使用`CompletableFuture.join()`方法获取所有异步方法的结果。这样可以保证所有异步方法执行完毕后,再返回结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)