public class ContainerNotSafeDemo {
public static void main(String[] args){
Set set = new HashSet<>();//线程不安全,报java.util.ConcurrentModificationException
for (int i=1;i<30;i++){
new Thread(()->{
set.add(UUID.randomUUID().toString().substring(0,8));
System.out.println(set);
},String.valueOf(i)).start();
}
}
}
2、线程安全写法
public class ContainerNotSafeDemo {
public static void main(String[] args){
// Set set = new HashSet<>();//线程不安全,报java.util.ConcurrentModificationException
Set set = new CopyOnWriteArraySet<>();//线程安全
for (int i=1;i<30;i++){
new Thread(()->{
set.add(UUID.randomUUID().toString().substring(0,8));
System.out.println(set);
},String.valueOf(i)).start();
}
}
}
HashSet底层是HashMap,key是e,value是PRESENT,key是唯一且无序的
private static final Object PRESENT = new Object();
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
3、Map
HashMap map = new HashMap<>();//线程不安全
Map map1 = new ConcurrentHashMap<>();//线程安全
Map
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)