Java开启50条线程,平均处理一个位置长度的List,可能长度会小于50,怎么实现?并写出当list长度为70时,是否会开启50个线程?
时间: 2024-03-09 21:47:35 浏览: 59
可以使用线程池来实现开启50条线程,平均处理一个位置长度的List,代码如下:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadDemo {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
// 初始化list
for (int i = 0; i < 70; i++) {
list.add(i);
}
// 计算每个线程处理的长度
int threadNum = 50;
int avgCount = list.size() / threadNum;
int modCount = list.size() % threadNum;
// 创建线程池
ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
int index = 0;
for (int i = 0; i < threadNum; i++) {
int count = avgCount;
if (modCount > 0) {
count++;
modCount--;
}
List<Integer> subList = list.subList(index, index + count);
index += count;
executorService.execute(new SubListThread(subList));
}
// 关闭线程池
executorService.shutdown();
}
}
class SubListThread implements Runnable {
private List<Integer> subList;
public SubListThread(List<Integer> subList) {
this.subList = subList;
}
@Override
public void run() {
// 处理subList
for (Integer i : subList) {
// do something
}
}
}
```
当list长度为70时,会开启50个线程处理,其中有20个线程处理2个元素,另外30个线程处理1个元素。
阅读全文