龙空技术网

java多线程实战四:自定义线程池实现多线程任务处理

AceTime 94

前言:

此刻咱们对“java多线程excel”大约比较关注,咱们都想要学习一些“java多线程excel”的相关知识。那么小编在网摘上搜集了一些有关“java多线程excel””的相关内容,希望我们能喜欢,小伙伴们一起来了解一下吧!

这里多线程处理excel批量数据导入功能,

1、首先将业务数据分成5批

2、ThreadPoolExecutor创建线程池,分5个运行,存活时间3分钟

3、将RequestAttributes对象设置为子线程共享

4、多线程处理任务

5、等待所有任务执行完成且等待队列中也无任务关闭线程池

poolExecutorVerify.shutdown();

6、 阻塞主线程, 直至线程池关闭

poolExecutorVerify.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS)

//将此次要导入的数据分批 分5批List<List<StudentImportModelExcel>> studentLists = ListUtil.averageAssign(data,5);//创建线程池 分5个运行  存活时间3分钟ThreadPoolExecutor poolExecutorVerify = new ThreadPoolExecutor(5, 5, 3, TimeUnit.MINUTES, new ArrayBlockingQueue<>(5));//将RequestAttributes对象设置为子线程共享ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();RequestContextHolder.setRequestAttributes(servletRequestAttributes, true);studentLists.forEach(list -> {   poolExecutorVerify.execute(() -> {	  StudentImportModelExcel studentModelExcel;      StringBuffer stringBufferJoint = new StringBuffer();      for (int i = 0; i < list.size(); i++) {         studentModelExcel = list.get(i);         StudentImportModelExcel excel = studentModelExcel;         Student student = new Student();         BeanUtil.copy(excel, student);         if (!PatternValidate.isYear(student.getYears())) {            stringBufferJoint.append("<br>" + "第" + excel.getIndex() + "行," + "年份格式错误:" + student.getYears());         }      }      stringBuffer.append(stringBufferJoint);   });});// 所有任务执行完成且等待队列中也无任务关闭线程池poolExecutorVerify.shutdown();// 阻塞主线程, 直至线程池关闭poolExecutorVerify.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);if (!stringBuffer.toString().equals("")) {   throw new XhjServiceException(stringBuffer.toString());}

标签: #java多线程excel