场景:使用线程池异步插入数据,等所有插入完成后返回执行成功信息。
用了@Async方法之后,发现主线程已经返回给前端了,说我已经把数据都插完了,但实际上还有其他子线程在背后偷偷摸摸插数据。。。这个有点过分吧?
在网上查找了许多方法,都不太合我胃口。。。
其中这篇给我的灵感挺多的:https://www.cnblogs.com/lixin-link/p/10998058.html
感谢!!
主要还是靠用Future来解决问题的
List<Future> futureList = new ArrayList<>();
for (List<Pojo> list : lists) {
//下面这个方法在方法上使用了@Async注解的
Future future = service.insertBatch(list);
futureList.add(future);
}
while (true) {
if (null != futureList) {
boolean isAllDone = true;
for (Future future : futureList) {
if (null == future || !future.isDone()) {
isAllDone = false;
}
}
if (isAllDone) {
break;
}
}
}
insertBatch方法大致代码如下(〃'▽'〃)
@Async
public Future insertBatch(List<Pojo> list) {
if (!CollectionUtils.isEmpty(list)) {
pojoMapper.insertBatch(list);
}
//返回需要用AsyncResult类,我也没试过其他的
return new AsyncResult(null);
}
最后我得到了~
没辍!这就是我要的~٩(๑>◡<๑)۶
告辞!