@Resource private SqlSessionTemplate sqlSessionTemplate;
public void threadInsert(List<StudentVO> 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<List<StudentVO>> lists = this.averageAssign(studentVOList, 5); Thread[] threads = new Thread[lists.size()]; //监控子线程执行完毕,再执行主线程,要不然会导致主线程关闭,子线程也会随着关闭 CountDownLatch countDownLatch = new CountDownLatch(lists.size()); for (int i = 0; i < lists.size(); i++) { List<StudentVO> list = lists.get(i); threads[i] = new Thread(() -> { try { //批量添加,mybatisPlus 中自带的 batch 方法 cacheTestMapper.batchInsert(list); } finally { countDownLatch.countDown(); } }); } for (int i = 0; i < lists.size(); i++) { executorService.execute(threads[i]); } //当子线程执行完毕时,主线程再往下执行 countDownLatch.await(); System.out.println("添加完毕"); connection.commit(); long end = System.currentTimeMillis(); System.out.println("多线程耗时:" + (end - start)); } catch (Exception e) { connection.rollback(); throw new RuntimeException("002 出现异常:" + e.getMessage()); } finally { connection.close(); } } 