异常 002 出现异常:connection closed,大佬们求教,是不是多线程影响到了,下面是方法

查看 72|回复 5
作者:Bryant0814   
@Resource
private SqlSessionTemplate sqlSessionTemplate;
public void threadInsert(List studentVOList) throws SQLException {
    long start = System.currentTimeMillis();
    Connection connection = sqlSessionTemplate.getConnection();
    CacheTestMapper cacheTestMapper
            = sqlSessionTemplate
            .getSqlSessionFactory()
            .openSession()
            .getMapper(CacheTestMapper.class);
    try {
        //设置手动提交
        connection.setAutoCommit(false);
        //先删除数据
        cacheTestMapper.deleteStudentById(1L);
        //获取线程池
        ExecutorService executorService = ExecutorUtil.getThreadPool();
        //拆分数据创建任务
        List> lists = this.averageAssign(studentVOList, 5);
        Thread[] threads = new Thread[lists.size()];
        //监控子线程执行完毕,再执行主线程,要不然会导致主线程关闭,子线程也会随着关闭
        CountDownLatch countDownLatch = new CountDownLatch(lists.size());
        for (int i = 0; i  list = lists.get(i);
            threads[i] = new Thread(() -> {
                try {
                    //批量添加,mybatisPlus 中自带的 batch 方法
                    cacheTestMapper.batchInsert(list);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        for (int i = 0; i

list, int, threads, thread

MoonWalker   
finally 里的代码比 Thread 里的代码先运行
Bryant0814
OP
  
@MoonWalker 这个 CountDownLatch 不是监控了子线程吗
cheng6563   
jdbc 不一定是线程安全的
Bryant0814
OP
  
@cheng6563 结合我这个说一下
mango88   
看上去你的 batchInsert 并没有用到你提前存下的 connection
您需要登录后才可以回帖 登录 | 立即注册

返回顶部