在日常开发过程中,很可能会碰到很重的for循环(即循环内存在大耗时操作),使用多线程执行for循环的话,可以大大的优化性能。
// ---------------新建一个线程池(static形式)------------------------------
private static ThreadPool pool =
ThreadPools.newCachedThreadPool(PersonPlanEventServiceHelper.class.getName(), 5,
10);
public static void insertLeavePersonPlanByThread(List<Long> businessIds) {
// <休假信息ID,休假信息DObj>
Map<Long, DynamicObject> leaveDobjMap = getLeaveDobjMap(businessIds);
// <制造人员ID,set<工作组>>
List<Long> manuPersonIds = leaveDobjMap.entrySet().stream().map(t -> t.getValue().getLong("hx_user.id")).collect(Collectors.toList());
Map<Long, Set<Long>> workGroups = getWorkGroupsByPerson(manuPersonIds);
if (leaveDobjMap != null && leaveDobjMap.size() > 0 && workGroups.size() > 0) {
List<DynamicObject> insertPersonPlans = Collections.synchronizedList(new ArrayList<>(2));
CountDownLatch downLatch = new CountDownLatch(businessIds.size());
for (Long businessId : businessIds) {
pool.execute(new Runnable() {
@Override
public void run() {
try {
generateLeaveInsertObj(businessId, insertPersonPlans, leaveDobjMap, workGroups);
} catch (Exception e) {
logger.info("循环开启多线程保存,调用下游出现错误,异常:" + e.getMessage());
} finally {
downLatch.countDown();
}
}
});
}
// 主线程需要等待子任务线程执行完,结果汇总之后,主线程继续往下执行
try {
// 等待30分钟,没有等到结果就退出
downLatch.await(30, TimeUnit.MINUTES);
} catch (Exception e) {
logger.error("主线程等待超时,异常:" + e.getMessage());
}
SaveServiceHelper.save(insertPersonPlans.toArray(new DynamicObject[0]));
}
}