集合线程安全问题
List不安全用CopyOnWriteArrayList解决
CopyOnwrite 写入时复制,计算机程序设计领域的一种优化策略;
多个线程调用的时候,List,读取的时候,固定的,写入(覆盖)
在写入的时候避免覆盖,造成数据问题!
读写分离
CopyOnWriteArrayList 比 Vector 好在哪里?
Vector用了锁 拖慢进程
public class Test1 {
public static void main(String[] args) {
/**
*解决方案;
*1、List<String> List = new Vector<>( );
*2、List<String> list = collections.synchronizedList(new ArrayList<>())
*3、List<String> list = new CopyOnWriteArrayList<>();
*/
final List<String> list = new CopyOnWriteArrayList<>();
for (int i = 1; i < 3; i++) {
new Thread(()->{
list.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(list);
},String.valueOf(i)).start();
}
}
}
Set不安全用CopyOnWriteArrayList解决
public class Test2Set {
public static void main(String[] args) {
//Set<String> set = new HashSet<>();
//Set<String> set = Collections.synchronizedSet(new HashSet<>());
Set<String> set = new CopyOnWriteArraySet<>();
for (int i = 1; i <10 ; i++) {
new Thread(()->{
set.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(set);
},String.valueOf(i)).start();
}
}
}
HashMap不安全用ConcurrentHashMap
public class MapTest {
public static void main(String[] args) {
Map<String,String> map = new ConcurrentHashMap<>();
for (int i = 1; i <10 ; i++) {
new Thread(()->{
map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0,5));
System.out.println(map);
},String.valueOf(i)).start();
}
}
}