java实现线程池(附完整源码)
时间: 2023-07-07 16:45:43 浏览: 94
下面是一个简单的Java实现线程池的示例代码:
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPool {
public static void main(String[] args) {
// 创建一个固定大小的线程池,大小为5
ExecutorService executorService = Executors.newFixedThreadPool(5);
// 向线程池提交任务
for (int i = 0; i < 10; i++) {
executorService.submit(new Task(i));
}
// 关闭线程池
executorService.shutdown();
}
static class Task implements Runnable {
private int taskId;
public Task(int taskId) {
this.taskId = taskId;
}
@Override
public void run() {
System.out.println("Task " + taskId + " is running.");
}
}
}
```
在这个例子中,我们使用了 Java 提供的 ExecutorService 接口和 Executors 工具类来实现线程池。具体而言,我们通过调用 Executors.newFixedThreadPool() 方法来创建一个固定大小的线程池,大小为 5。然后,我们使用 for 循环向线程池提交 10 个任务,每个任务都是一个实现了 Runnable 接口的 Task 对象。在每个 Task 的 run() 方法中,我们简单地输出一条信息,表示该任务正在运行。最后,我们通过调用 executorService.shutdown() 方法来关闭线程池。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)