Executors.newFixedThreadPool使用方法
时间: 2024-06-16 21:06:41
浏览: 18
[executor](https://geek.csdn.net/educolumn/566e7c26c9421a641f601efb455fcd63?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083)s.newFixedThreadPool是Java中的一个线程池工具类,用于创建一个固定大小的线程池。它的使用方法如下:
1. 导入必要的包:
```java
import java.util.concurrent.[executor](https://geek.csdn.net/educolumn/566e7c26c9421a641f601efb455fcd63?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083)Service;
import java.util.concurrent.[executor](https://geek.csdn.net/educolumn/566e7c26c9421a641f601efb455fcd63?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083)s;
2. 创建一个固定大小的线程池:
```java
int poolSize = 5; // 线程池大小
[executor](https://geek.csdn.net/educolumn/566e7c26c9421a641f601efb455fcd63?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083)Service [executor](https://geek.csdn.net/educolumn/566e7c26c9421a641f601efb455fcd63?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083) = Executors.newFixedThreadPool(poolSize);
3. 提交任务给线程池执行:
```java
executor.execute(new Runnable() {
@Override
public void run() {
// 执行任务的代码
4. 关闭线程池:
```java
executor.shutdown();
```
相关推荐
















