需要在循环中批量处理延时任务 需要用到多线程 批处理 并且需要等待全部完成
@GetMapping("/testThread")
public R<?> testThread(int max) {
// 1. 创建定长线程池对象 & 设置线程池线程数量固定为3
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < max; i++) {
logger.debug("testThread:" + i);
fixedThreadPool.execute(new MyRunnable(i));
}
//延时等待线程池中的任务全部完成
fixedThreadPool.shutdown();
try {
fixedThreadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
logger.debug("完成任务" );
return R.ok();
}
class MyRunnable implements Runnable {
int i = 0;
public MyRunnable(int i) {
this.i = i;
}
@Override
public void run() {
String id = Thread.currentThread().getId() + "";
try {
int sleep = RandomUtils.nextInt(100, 10000);
logger.debug(id + ":workTime:" + sleep);
Thread.sleep(sleep);
} catch (InterruptedException e) {
e.printStackTrace();
}
logger.debug(id + ":workData:" + i);
}
}
日志
14:18:31.068 [http-nio-7000-exec-2] DEBUG c.r.a.c.PublicController - [testThread,70] - testThread:0
14:18:31.069 [http-nio-7000-exec-2] DEBUG c.r.a.c.PublicController - [testThread,70] - testThread:1
14:18:31.069 [http-nio-7000-exec-2] DEBUG c.r.a.c.PublicController - [testThread,70] - testThread:2
14:18:31.069 [pool-8-thread-1] DEBUG c.r.a.c.PublicController - [run,54] - 190:workTime:3242
14:18:31.069 [pool-8-thread-2] DEBUG c.r.a.c.PublicController - [run,54] - 191:workTime:9651
14:18:31.069 [pool-8-thread-3] DEBUG c.r.a.c.PublicController - [run,54] - 192:workTime:8547
14:18:34.312 [pool-8-thread-1] DEBUG c.r.a.c.PublicController - [run,59] - 190:workData:0
14:18:39.617 [pool-8-thread-3] DEBUG c.r.a.c.PublicController - [run,59] - 192:workData:2
14:18:40.721 [pool-8-thread-2] DEBUG c.r.a.c.PublicController - [run,59] - 191:workData:1
14:18:40.721 [http-nio-7000-exec-2] DEBUG c.r.a.c.PublicController - [testThread,79] - 完成