List
package com.luoKing.unsafe;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
public class listTest {
/*
* 使用 List会出现 ConcurrentModificationException:并发修改异常
* 解决方法
* 1. List<String> list = new CopyOnWriteArrayList<>();
* 2. List<String> list = new Vector<>();
* 为什么使用CopyOnWriteArrayList而不使用Vector?
* 应为vector.add方法是同步方法,CopyOnWriteArrayList.add方法中用lock锁达到同步
* 我们知道synchronized运行效率比Lock锁慢
*
* */
public static void main(String[] args) {
List<String> list = new Vector<>();
for (int i = 1; i <= 10; i++) {
// try {
// TimeUnit.SECONDS.sleep(1);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
new Thread(()->{
list.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(list);
},String.valueOf(i)).start();
}
}
}
Set
package com.luoKing.unsafe;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;
/*
* 使用HashSet会出现线程不安全问题 ConcurrentModificationException:
* 解决方法
* 1. Set<Object> set = new CopyOnWriteArraySet<>();
* 2. Set<Object> set = Collections.synchronizedSet(new HashSet<>());
* */
public class SetTest {
public static void main(String[] args) {
// HashSet set = new HashSet();
Set<Object> set = Collections.synchronizedSet(new HashSet<>());
for (int i = 0; i < 20; i++) {
new Thread(()->{
set.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(set);
}).start();
}
}
}
Map
package com.luoKing.unsafe;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/*
* 单纯的HashMap会有并发问题,ConcurrentModificationException:同步修改异常
*解决方法:
* Map<String, String> map = new ConcurrentHashMap<>();
* */
public class MapTest {
public static void main(String[] args) {
Map<String, String> map = new ConcurrentHashMap<>();
for (int i = 0; i < 200; i++) {
new Thread(()->{
map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0,5));
System.out.println(map);
},String.valueOf(i)).start();
}
}
}