一、set集合并发
我们用 Set<String> set = new HashSet<>(); 会线程多的话会产生并发修改ConcurrentModificationException
异常代码
public class SetText {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
for (int i = 0; i < 50; i++) {
new Thread(()->{
set.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(set);
}).start();
}
}
}
会发生异常
第一种:解决用Collections 集合工具类解决
public class SetText {
public static void main(String[] args) {
Set<String> set = Collections.synchronizedSet(new HashSet<>());
for (int i = 0; i < 50; i++) {
new Thread(()->{
set.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(set);
}).start();
}
}
}
第二种:JUC的方法
Set<String> set = new CopyOnWriteArraySet<>(new HashSet<>());
for (int i = 0; i < 50; i++) {
new Thread(()->{
set.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(set);
}).start();
}
}
List集合与Set集合同理