使用场景
在我们的业务逻辑中,会有很多定时任务或者手动跑批任务,当我们有时候对时间效率要求比较高时,我们可能就需要用多线程来执行这个任务,假如我们的业务逻辑有顺序,需要执行A逻辑完成后才能执行B逻辑,那么这时候线程执行完还需要等待其他线程。
代码DEMO
具体的业务逻辑根据自己的业务逻辑来设计,我这里给出我的一种写法
public void updateAllPersonData() throws Exception {
if (flag) {
logger.error("任务正在运行,请稍后...");
return;
}
flag = true;
try {
List<Map<String, String>> personArr = new ArrayList();
int cy = 10000;
int allSize = personArr.size();
logger.debug("返回的所有人员条数:" + allSize);
ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) SpringBeanUtil.getBean("dingTaskExecutor");
int threadNum = allSize%cy >0?allSize/cy +1:allSize/cy ;
CountDownLatch attendDownLatch = new CountDownLatch(threadNum);
for (int i=0; i<threadNum; i++) {
int endSize = (i+1) * cy ;
if (endSize > allSize) {
endSize = allSize;
}
List<Map<String, String>> thisList = personArr.subList(i*1000, endSize);
taskExecutor.execute(new SyncShrPersonRunner(thisList, attendDownLatch));
}
attendDownLatch.await(6, TimeUnit.HOURS);
logger.debug("同步全量人员数据结束");
}catch (Exception e) {
logger.error("同步全量人员数据异常", e);
} finally {
flag = false;
}
}
class SyncShrPersonRunner implements Runnable {
private final List<Map<String, String>> personList;
private final SysQuartzJobContext context;
private final CountDownLatch countDownLatch;
public SyncShrPersonRunner(List<Map<String, String>> personList, CountDownLatch countDownLatch) {
this.personList = personList;
this.context = context;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
try{
for (Map<String, String> map : personList) {
}
} catch (Exception e) {
logger.error("更新异常:", e);
} finally {
countDownLatch.countDown();
}
}
}
结语
这是一个小小的demo,希望可以帮助到有需要的人,我也是刚好有这个场景,多以记录一下。代码删除了一些业务逻辑,如有报错请自行补充完整。