把下面代码修改为根据pushMailboxList的数量按每10条为一批多线程分批执行 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 12:08:49 浏览: 208
将代码修改为根据 pushMailboxList 的数量按每 10 条为一批使用多线程分批执行的代码可能长这样:
```
List<List<PushMailbox>> pushMailboxLists = Lists.partition(pushMailboxList, 10);
for (List<PushMailbox> list : pushMailboxLists) {
// 使用多线程运行
ExecutorService executor = Executors.newFixedThreadPool(list.size());
for (PushMailbox item : list) {
executor.execute(() -> {
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();
while (!executor.isTerminated()) {
}
}
```
注意,上面的代码是假设 pushMailboxList 中的元素个数为n,则将其分为 n/10 个列表。每个列表都会在一个单独的线程中并行执行。
阅读全文