CompletableFuture代码中创建新的线程池并使用线程池
时间: 2023-10-18 17:51:22 浏览: 96
在`CompletableFuture`的代码中,你可以通过创建新的线程池来执行异步任务,并指定该线程池用于`CompletableFuture`的执行。
下面是一个示例,演示如何在`CompletableFuture`中创建新的线程池并使用它:
```java
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CompletableFutureExample {
public static void main(String[] args) {
// 创建一个新的线程池
ExecutorService executor = Executors.newFixedThreadPool(5);
// 使用线程池执行异步任务
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// 异步任务逻辑
return "Hello, World!";
}, executor);
// 在异步任务完成后执行回调任务
future.thenAccept(result -> {
// 回调任务逻辑
System.out.println("Result: " + result);
});
// 关闭线程池
executor.shutdown();
}
}
```
在上面的示例中,我们使用`Executors.newFixedThreadPool()`方法创建了一个固定大小为5的新线程池`executor`。然后,我们使用`supplyAsync()`方法将异步任务提交到该线程池中执行。接下来,我们使用`thenAccept()`方法注册了一个回调任务,在异步任务完成后输出结果。
通过创建新的线程池,你可以更好地控制并发执行的线程数量,并可根据实际需求灵活地配置线程池参数。在不需要使用线程池时,记得及时关闭线程池以释放资源。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)