一:在run()方法里写插入
package com.smartdata.pms.thread;
import com.smartdata.pms.entity.PmsProduct;
import com.smartdata.pms.mapper.PmsProductMapper;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
/**
* @ProjectName: smartdata
* @Package: com.smartdata.pms.thread
* @ClassName: InsertBatchRun
* @Author: heluwei
* @Description:
* @Date: 2020/3/22 16:36
* @Version: 1.0
*/
@ Slf4j
public class InsertBatchRun implements Runnable {
//数据层访问
private PmsProductMapper pmsProductMapper;
//具体插入批次
private int batch;
//插入的数据
private List < PmsProduct > list;
public InsertBatchRun(PmsProductMapper pmsProductMapper, List < PmsProduct > list, int batch) {
this.pmsProductMapper = pmsProductMapper;
this.list = list;
this.batch = batch;
}
@ Override
public void run() {
try {
for (int i = 0; i < list.size(); i++) {
this.pmsProductMapper.insert(list.get(i));
}
log.info("第" + this.batch + "批次插入成功");
} catch (Exception e) {
log.error("第" + this.batch + "批次插入失败");
}
}
}
注意:在使用***Mapper的时候。不能使用@Autowired,因为多线程环境下,防止注入。
二:使用线程池
package com.smartdata.pms.utils;
import com.smartdata.pms.entity.PmsProduct;
import com.smartdata.pms.mapper.PmsProductMapper;
import com.smartdata.pms.thread.InsertBatchRun;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**