List<UserEo> userEoList = comDataComponent.getUserListByUid();int batchSize = 1000; // 每批次处理1000个用户int threadCount = (userEoList.size() + batchSize - 1) / batchSize; // 计算需要开启的线程数ExecutorService executorService = Executors.newFixedThreadPool(threadCount);for (int i = 0; i < threadCount; i++) { int start = i * batchSize; int end = Math.min(start + batchSize, userEoList.size()); List<UserEo> subList = userEoList.subList(start, end); executorService.submit(() -> { for (UserEo userEo : subList) { List<DataPermissionSchema> userDataPermissionSchema = getUserDataPermissionSchema(userEo.getUserUid(), userEo.getOrgCode()); String redisKey = SystemsConstant.DATA_PERMISSION_SCHEMA + userEo.getUserUid(); redisTemplate.executePipelined((RedisCallback<Object>) connection -> { connection.set(redisTemplate.getKeySerializer().serialize(redisKey), redisTemplate.getValueSerializer().serialize(ObjectUtil.toString(userDataPermissionSchema))); return null; }); } });}executorService.shutdown();executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);改为手动创建线程池
时间: 2024-01-02 07:02:53 浏览: 152
ExecutorService线程池
可以将原来的代码改为手动创建线程池的方式,如下所示:
```
List<UserEo> userEoList = comDataComponent.getUserListByUid();
int batchSize = 1000; // 每批次处理1000个用户
int threadCount = (userEoList.size() + batchSize - 1) / batchSize; // 计算需要开启的线程数
ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
for (int i = 0; i < threadCount; i++) {
int start = i * batchSize;
int end = Math.min(start + batchSize, userEoList.size());
List<UserEo> subList = userEoList.subList(start, end);
Thread thread = new Thread(() -> {
for (UserEo userEo : subList) {
List<DataPermissionSchema> userDataPermissionSchema = getUserDataPermissionSchema(userEo.getUserUid(), userEo.getOrgCode());
String redisKey = SystemsConstant.DATA_PERMISSION_SCHEMA + userEo.getUserUid();
redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
connection.set(redisTemplate.getKeySerializer().serialize(redisKey), redisTemplate.getValueSerializer().serialize(ObjectUtil.toString(userDataPermissionSchema)));
return null;
});
}
});
executorService.submit(thread);
}
executorService.shutdown();
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
```
这个代码中,我们手动创建了线程池,并且使用了 `Thread` 类来创建线程。我们将任务放入线程中运行,并且使用 `executorService.submit(thread)` 方法将线程提交到线程池中。最后,我们关闭线程池,并等待所有任务执行完毕。
阅读全文