把这段代码修改为多线程分批执行没20条分一批 if (ObjectUtil.isNotEmpty(pushMailboxList)) { pushMailboxList.stream().forEach(item -> { Township byId = townshipService.getById(item.getPushOrgid()); try { String email = byId.getEmail(); if (StrUtil.isNotBlank(email)) { String date = DateTime.now().toString(DatePattern.CHINESE_DATE_TIME_PATTERN); String content = "金平县气象局于" + date + ",发布了" + repProductContent.getReportName() + "气象服务通知,请您查收并注意做好防范工作。"; //发送邮件 MailUtil.send(email, repProductContent.getReportName(), content, false, FileUtil.file(filePath)); item.setIzEmailSuccess(1); pushMailboxList1.add(item); } else { item.setIzEmailSuccess(0); pushMailboxList1.add(item); } } catch (Exception e) { item.setIzEmailSuccess(0); pushMailboxList1.add(item); e.printStackTrace(); } }); }
时间: 2023-02-08 22:59:01 浏览: 98
如果要将上述代码修改为多线程分批执行每20条分一批,可以这样做:
1. 将原来的forEach循环替换为for循环,并设置循环变量i和每批数量batchSize(20)
2. 使用Java中的线程池创建一个线程池,并在循环中提交任务
3. 在任务中使用subList方法将原始数据分成每批数量的数据块
4. 等待所有任务完成
示例代码如下:
```
if (ObjectUtil.isNotEmpty(pushMailboxList)) {
int batchSize = 20;
int listSize = pushMailboxList.size();
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < listSize; i += batchSize) {
List<PushMailbox> subList = pushMailboxList.subList(i, Math.min(i + batchSize, listSize));
executor.submit(() -> {
subList.stream().forEach(item -> {
Township byId = townshipService.getById(item.getPushOrgid());
try {
String email = byId.getEmail();
if (StrUtil.isNotBlank(email)) {
String date = DateTime.now().toString(DatePattern.CHINESE_DATE_TIME_PATTERN);
String content = "金平县气象局于" + date + ",发布了" + repProductContent.getReportName() + "气象服务通知,请您查收并注意做好防范工作。";
//发送邮件
MailUtil.send(email, repProductContent.getReportName(), content, false, FileUtil.file(filePath));
item.setIzEmailSuccess(1);
pushMailboxList1.add(item);
} else {
item.setIzEmailSuccess(0);
pushMailboxList1.add(item);
}
} catch (Exception e) {
item.setIzEmailSuccess(0);
pushMailboxList1.add(item);
e.printStackTrace();
}
});
});
}
executor.shutdown();
try {
阅读全文