接手的项目里有这样一段代码,大概就是数据库返回的list使用多线程补充些数据,但是实际运行起来的时候 briefVo补充的数据有概率会发生混乱-->briefVo指向了list中的其他项。求助,这段代码究竟是哪里有问题?
// int countThread =list.size();
// ExecutorService threadPool = Executors.newFixedThreadPool(countThread);
// //计数器
// final CountDownLatch countDownLatch = new CountDownLatch(countThread-1);
// Future[] futures = new Future[countThread];
// for(int x=0; x<=(countThread-1); x++) {
// Inv sub = list.get(x);
// futures[x] = threadPool.submit(() -> {
// try {
// handleData(sub);
// }catch(Exception e) {
// e.printStackTrace();
// LOG.error(e,e);
// throw e;
// }finally {
// //计数器-1
// countDownLatch.countDown();
// }
// return null;
// });
// }
// try {
// countDownLatch.await();
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// }finally {
// threadPool.shutdown();
// }
public void handleData( Inv sub){
BriefVo briefVo = bonService.getBriefById(sub.getId());
sub.setBriefVo(issuerBriefVo);
}
// final CountDownLatch countDownLatch = new CountDownLatch(countThread-1);
不用减1
线程数为4
new CountDownLatch(3);
for循环四次 但其实到第三次的时候count已经减到0了 就直接方形await方法 但是其实还有个线程有可能没执行完
建议 了解下 CompletionService 或者 CompletableFuture
第四个线程有可能优先抢到cup运行出结果 也可能抢不到 然后mai方法就结束了
所以demo有时候重现得出来 有时候出不来
看过也觉得完全没问题,写demo运行过,不能重现,静待大神出现~~