// 将集合转换成线程安全的集合
List<Map<String, Object>> synListItem = Collections.synchronizedList(new ArrayList<>());
//创建一个CountDownLatch类,构造入参线程数
CountDownLatch countDownLatch = new CountDownLatch(listItem.size());
Iterator<Map<String, Object>> iterator = listItem.iterator();
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
while (iterator.hasNext()) {
cachedThreadPool.submit(() -> {
Map<String, Object> map = iterator.next();
// linkIds 为空表示开关未配置
try {
xxxx
synListItem.add(map);
} catch (Exception e) {
e.printStackTrace();
} finally {
//该线程执行完毕-1
countDownLatch.countDown();
}
});
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 后面如果不进行多线程操作,建议转为正常的List集合,避免synchronized 加锁导致性能降低
List<Map<String, Object>> newListItem = new ArrayList<>(synListItem);
使用线程池+线程计数器迭代器删除List集合元素(新建对象版)
最新推荐文章于 2024-07-13 20:20:50 发布