@Test public void testThreadPoolSplit() { List<Integer> ids = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 9, 8, 76, 41, 42, 43, 44); batchUpdate(ids); } public void batchUpdate(List<Integer> skuIds) { ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1); if (CollectionUtils.isNotEmpty(skuIds)) { int splitMaxNum = 7; //大量更新,超过20个,考虑多线程处理; if (skuIds.size() > splitMaxNum) { try { for (int i = 0; i < skuIds.size(); i = i + splitMaxNum) { List<Integer> newPurSkuList = skuIds.stream().skip(i).limit(splitMaxNum).collect(Collectors.toList()); executor.execute(() -> updateSku(newPurSkuList)); } executor.shutdown(); } catch (Exception e) { log.warn("批量更新Sku 失败"); } } else { updateSku(skuIds); } } } public void updateSku(List<Integer> skuList) { System.out.println(JSONObject.toJSONString(skuList)); }
//使用google guava对List进行分割 //使用guava对list进行分割 List<User> users = userService.findAll(); //按每50个一组分割 List<List<User>> parts = Lists.partition(users, 50); parts.stream().forEach(list -> { process(list); });
//common collections List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8); List<List<Integer>> subs = ListUtils.partition(intList, 3);