使用newFixedThreadPool() 操作方法去输出数据
时间: 2024-02-22 08:57:50 浏览: 15
以下是一个使用 `newFixedThreadPool()` 方法输出数据的示例代码:
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
// 创建一个固定大小为 5 的线程池
ExecutorService executor = Executors.newFixedThreadPool(5);
// 向线程池提交 10 个任务
for (int i = 0; i < 10; i++) {
executor.execute(new Task(i));
}
// 关闭线程池
executor.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 in thread " + Thread.currentThread().getName());
}
}
}
```
输出结果:
```
Task 0 is running in thread pool-1-thread-1
Task 1 is running in thread pool-1-thread-2
Task 2 is running in thread pool-1-thread-3
Task 3 is running in thread pool-1-thread-4
Task 4 is running in thread pool-1-thread-5
Task 5 is running in thread pool-1-thread-1
Task 6 is running in thread pool-1-thread-2
Task 7 is running in thread pool-1-thread-3
Task 8 is running in thread pool-1-thread-4
Task 9 is running in thread pool-1-thread-5
```
在这个示例中,我们创建了一个固定大小为 5 的线程池,并向线程池提交了 10 个任务。线程池会自动分配线程来执行任务,直到所有任务都被执行完毕。注意,在任务执行完毕后,我们需要调用线程池的 `shutdown()` 方法来关闭线程池。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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_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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)