ThreadPoolExecutor怎么实现5个线程执行100个任务
时间: 2023-08-12 08:03:18 浏览: 94
要使用ThreadPoolExecutor实现5个线程执行100个任务,你可以按照以下步骤进行操作:
1. 创建一个ThreadPoolExecutor对象,并设置核心线程数和最大线程数为5:
```java
ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
```
2. 循环提交100个任务给线程池执行,可以使用execute方法或submit方法:
```java
for (int i = 0; i < 100; i++) {
final int taskId = i;
executor.execute(() -> {
System.out.println("Task " + taskId + " is being executed by thread " + Thread.currentThread().getName());
// 执行具体的任务逻辑
});
}
```
3. 最后,调用shutdown方法关闭线程池,确保所有任务都执行完毕:
```java
executor.shutdown();
```
完整的示例代码如下:
```java
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
for (int i = 0; i < 100; i++) {
final int taskId = i;
executor.execute(() -> {
System.out.println("Task " + taskId + " is being executed by thread " + Thread.currentThread().getName());
// 执行具体的任务逻辑
});
}
executor.shutdown();
}
}
```
在上面的代码中,我们创建了一个ThreadPoolExecutor对象,并设置核心线程数和最大线程数都为5。然后,使用execute方法循环提交了100个任务给线程池执行。每个任务都会打印一条信息,显示当前任务正在被哪个线程执行。
最后,调用shutdown方法关闭线程池,确保所有任务都执行完毕。
阅读全文