public void runUpdate(List<SysSiteMapUrlBean> shoplist) throws Exception{
// 開始時間
long start = System.currentTimeMillis();
// 每5000條數據開啓一條線程
int threadSize = 5000;
// 總數據條數
int dataSize = shoplist.size();
// 線程數
int threadNum = dataSize / threadSize + 1;
// 定義標記,過濾threadNum爲整數
boolean special = dataSize % threadSize == 0;
// 創建一個線程池
ExecutorService exec = Executors.newFixedThreadPool(threadNum);
// 定義一個任務集合
List<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>();
Callable<Integer> task = null;
List<SysSiteMapUrlBean> cutList = null;
// 確定每條線程的數據
for (int i = 0; i < threadNum; i++) {
if (i == threadNum - 1) {
if (special) {
break;
}
cutList = shoplist.subList(threadSize * i, dataSize);
} else {
cutList = shoplist.subList(threadSize * i, threadSize * (i + 1));
}
System.out.println("第" + (i + 1) + "組:" + cutList.toString());
final List<SysSiteMapUrlBean> listStr = cutList;
task = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
//線程要執行的方法
sysSiteMapUrlService.batchAdd(listStr);
return 1;
}
};
// 這裏提交的任務容器列表和返回的Future列表存在順序對應的關係
tasks.add(task);
}
List<Future<Integer>> results = exec.invokeAll(tasks);
for (Future<Integer> future : results) {
System.out.println(future.get());
}
// 關閉線程池
exec.shutdown();
System.out.println("線程任務執行結束");
System.err.println("執行任務消耗了 :" + (System.currentTimeMillis() - start) + "毫秒");
}