/**
* 线程
* @param data //线程list
* @param batchNum //每次新增条数
* @throws InterruptedException
*/
private void batchDeal( List<User> data, int batchNum) throws InterruptedException {
int totalNum = data.size();
int pageNum = totalNum % batchNum == 0 ? totalNum / batchNum : totalNum / batchNum + 1;
ExecutorService executor = Executors.newFixedThreadPool(pageNum);
try {
CountDownLatch countDownLatch = new CountDownLatch(pageNum);
List<User> subData = null;
int fromIndex, toIndex;
for (int i = 0; i < pageNum; i++) {
fromIndex = i * batchNum;
toIndex = Math.min(totalNum, fromIndex + batchNum);
subData = data.subList(fromIndex, toIndex);
ImportTask task = new ImportTask(subData, countDownLatch);
executor.execute(task);
}
// 主线程必须在启动其它线程后立即调用CountDownLatch.await()方法,
// 这样主线程的操作就会在这个方法上阻塞,直到其它线程完成各自的任务。
// 计数器的值等于0时,主线程就能通过await()方法恢复执行自己的任务。
countDownLatch.await();
} finally {
// 关闭线程池,释放资源
executor.shutdown();
}
}
class ImportTask implements Runnable {
private List<User> list;
private CountDownLatch countDownLatch;
public ImportTask( List<User> data, CountDownLatch countDownLatch) {
this.list = data;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
if (null != list) {
userMapper.insertUserList(list);
}
// 发出线程任务完成的信号
countDownLatch.countDown();
}
}
java 线程池批量新增
最新推荐文章于 2024-01-04 14:54:08 发布