java利用线程池处理集合
java利用线程池处理集合
java用线程池处理集合问题
循环集合每多少条数据开启一个集合,此处每十万数据开启一个线程
public void testStr() {
List<BaseEntity> list = new ArrayList<>();
for (int i = 0; i < 2000000; i++) {
BaseEntity entity = new BaseEntity();
entity.setId("这是**一个**测试" + i);
list.add(entity);
}
long start = System.currentTimeMillis();
check = new ChineseCheck();
ExecutorService executor = Executors.newFixedThreadPool(5);
int size = list.size();
if (size > 100000) {
int batch = size % 100000 == 0 ? size / 100000 : size / 100000 + 1;
for (int j=0; j<batch; j++) {
int end = (j+1)*100000;
if (end > size) {
end = size;
}
List<BaseEntity> subList = list.subList(j*100000, end);
TestCallable callable = new TestCallable(subList, check);
executor.execute(callable);
}
}
executor.shutdown();
while (true) {
if (executor.isTerminated()) {
break;
}
}
long date = System.currentTimeMillis() - start;
System.out.println("======" + date + "======");
}
用时:1361 ms
两百万条数据做校验,每一条数据开一个线程
List<BaseEntity> list = new ArrayList<>();
for (int i = 0; i < 2000000; i++) {
BaseEntity entity = new BaseEntity();
entity.setId("这是**一个**测试" + i);
list.add(entity);
}
long start = System.currentTimeMillis();
check = new ChineseCheck();
ExecutorService executor = Executors.newFixedThreadPool(5);
for (BaseEntity entity: list) {
TestCallable callable = new TestCallable(entity, check);
executor.execute(callable);
}
executor.shutdown();
while (true) {
if (executor.isTerminated()) {
break;
}
}
long date = System.currentTimeMillis() - start;
System.out.println("======" + date + "======");
用时:29875 ms
以上两种情况对比,当使用线程池开启多线程的时候,每一个线程中校验多条数据,此时效率会高
可以按照这批数据的处理次数来创建线程池,规定线程池最大线程数,然后不大于这个线程数的时候可以按照处理次数来创建线程
此处,多个线程同用一个单例处理数据和多线程用不同的实例对象处理数据效果相同
即,此处循环list时,是否每次都new一个check