java ThreadPoolExecutor 创建5个线程池每个线程池平均分配list里面的数据list的size不一定有多少
以下是Java代码示例,使用ThreadPoolExecutor创建5个线程池,每个线程池平均分配list里面的数据:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
public class ThreadPoolDemo {
public static void main(String[] args) {
// 创建一个包含100个元素的List
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 100; i++) {
list.add(i);
}
// 创建一个包含5个线程池的线程池Executor
ExecutorService executor = Executors.newFixedThreadPool(5);
// 获取ThreadPoolExecutor对象,以便使用getActiveCount方法获取线程池中正在执行任务的线程数
ThreadPoolExecutor tpExecutor = (ThreadPoolExecutor) executor;
// 每个线程处理的元素数
int batchSize = list.size() / tpExecutor.getCorePoolSize();
// 创建5个任务,每个任务处理一个线程池中的元素
for (int i = 0; i < tpExecutor.getCorePoolSize(); i++) {
int startIndex = i * batchSize;
int endIndex = (i + 1) * batchSize;
if (i == tpExecutor.getCorePoolSize() - 1) {
endIndex = list.size();
}
List<Integer> subList = list.subList(startIndex, endIndex);
executor.execute(new Task(subList));
}
// 关闭线程池
executor.shutdown();
}
}
class Task implements Runnable {
private List<Integer> list;
public Task(List<Integer> list) {
this.list = list;
}
@Override
public void run() {
for (Integer num : list) {
// 处理元素的逻辑
System.out.println(Thread.currentThread().getName() + "处理了元素:" + num);
}
}
}
在这个示例中,我们先创建了一个包含100个元素的List。然后,我们创建了一个包含5个线程池的线程池Executor,并获取了ThreadPoolExecutor对象以便使用getActiveCount方法获取线程池中正在执行任务的线程数。
接下来,我们计算每个线程处理的元素数,然后创建5个任务,每个任务处理一个线程池中的元素。在每个任务的run方法中,我们使用for循环处理元素的逻辑。
最后,我们关闭了线程池。输出结果如下:
pool-1-thread-1处理了元素:0
pool-1-thread-2处理了元素:1
pool-1-thread-3处理了元素:2
pool-1-thread-4处理了元素:3
pool-1-thread-5处理了元素:4
pool-1-thread-1处理了元素:5
pool-1-thread-2处理了元素:6
pool-1-thread-3处理了元素:7
pool-1-thread-5处理了元素:8
pool-1-thread-4处理了元素:9
...
原文地址: http://www.cveoy.top/t/topic/bVUa 著作权归作者所有。请勿转载和采集!