@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();
}
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.