前言
记录项目中遇到的问题
需要使用多线程处理数据,但同时也要返回值。
List<List<String>> partition = Lists.partition(ids, 1000);
int taskSize = 5;
// 创建一个线程池
ThreadPoolExecutor executor = new ThreadPoolExecutor(taskSize, taskSize+1, 1000, TimeUnit.MINUTES, new LinkedBlockingDeque<>());
/*创建List用来接收多线程返回的内容,泛型里面可以自定义,String或者对象亦或者其他类型*/
List<Map<String, Object>> listret = new ArrayList<>();
// 同步工具类,让主线程一直等待,直到子线程执行完后再执行
CountDownLatch downLatch = new CountDownLatch(partition.size());
// 循环任务的List
for (List<String> stringList : partition) {
// 启用开启多个线程
executor.execute(() -> {
try {
// 开始调用具体业务代码
List<Map<String, Object>> mapRet = xxMapper.selectTest(stringList);
listret.addAll(mapRet);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 业务逻辑处理完毕,计数器减一【当前线程处理任务完毕,线程释放进入线程池,等待处理下一个任务】
downLatch.countDown();
}
});
}
// 主线程需要等待子任务线程执行完,结果汇总之后,主线程继续往下执行
try {
downLatch.await();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("系统处理超时,请稍后再试");
}
// 关闭线程池
executor.shutdown();
部分操作异步 整体同步
ExecutorService threadPool = Executors.newFixedThreadPool(5);
// 返回值
Map<String, String> result = new ConcurrentHashMap();
// 添加时间标点查看时间
long startTime = System.currentTimeMillis();
CompletableFuture.allOf(
CompletableFuture.runAsync(() -> result.put("key1", xxmethod1()), threadPool),
CompletableFuture.runAsync(() -> result.put("key2", xxmethod2()), threadPool),
CompletableFuture.runAsync(() -> result.put("key3", xxmethod3()), threadPool)
).join();
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);