java 怎么使用线程池
时间: 2023-12-06 08:36:06 浏览: 48
Java中使用线程池可以提高程序的效率和性能,下面是使用线程池的步骤和示例代码:
1. 创建线程池对象
```java
ExecutorService executorService = Executors.newFixedThreadPool(5); // 创建一个固定大小为5的线程池
```
2. 创建任务
```java
Runnable task = new Runnable() {
@Override
public void run() {
// 任务执行的代码
}
};
```
3. 提交任务到线程池中执行
```java
executorService.submit(task);
```
4. 关闭线程池
```java
executorService.shutdown();
```
完整示例代码:
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolDemo {
public static void main(String[] args) {
// 创建一个固定大小为5的线程池
ExecutorService executorService = Executors.newFixedThreadPool(5);
// 创建10个任务并提交到线程池中执行
for (int i = 0; i < 10; i++) {
Runnable task = new Runnable() {
@Override
public void run() {
System.out.println("线程" + Thread.currentThread().getName() + "正在执行任务");
}
};
executorService.submit(task);
}
// 关闭线程池
executorService.shutdown();
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)