int threadSize = 20;
// 当前时间对应的毫秒数
long startTime1 = System.currentTimeMillis();
long startTime2 = 0;
try {
Future<String> task = null;
List<String> cutList;
// 线程数
int threadNum = mailnoList.size() / threadSize + 1;
// 定义标记,过滤threadNum为整数
boolean special = mailnoList.size() % threadSize == 0;
List<Future> futureList = new ArrayList<>(20);
for (int i = 0; i < threadNum; i++) {
if (i == threadNum - 1) {
if (special) {
break;
}
cutList = mailnoList.subList(threadSize * i, mailnoList.size());
} else {
cutList = mailnoList.subList(threadSize * i, threadSize * (i + 1));
}
StaticLog.info("线程执行:" + i);
startTime2 = System.currentTimeMillis();
StaticLog.info("线程执行开始时间:" + startTime2);
task = batchGetWaybillInfo(cutList);
futureList.add(task);
}
//获取所有线程最终是否完成状态
//isDone方法表示任务是否已经完成,若任务完成,则返回true;
for (Future<?> future : futureList) {
while (true) {
if (future.isDone()) {
//当前线程完成结束此次轮询
break;
} else {
//每次轮询休息1mm 避免CPU高速轮询耗空CPU
Thread.sleep(1);
}
}
}
//结束时间
long endTime1 = System.currentTimeMillis();
float seconds = (endTime1 - startTime1) / 1000F;
StaticLog.info("下单总耗时(秒):" + Float.toString(seconds));
} catch (Exception e) {
e.printStackTrace();
StaticLog.debug(e.toString());
}
多线程执行
最新推荐文章于 2022-04-30 16:33:28 发布