1 我们知道 ArrayList 线程不安全,请编写一个不安全的案例并给出解决方案?

  • 故障现象
  1. public class UnsafeListDemo {
  2. public static void main(String[] args) {
  3. List<Integer> list = new ArrayList<>();
  4. Random random = new Random();
  5. for (int i = 0; i < 100; i++) {
  6. new Thread(() -> {
  7. list.add(random.nextInt(10));
  8. System.out.println(list);
  9. }).start();
  10. }
  11. }
  12. }
  • 发现报 java.util.ConcurrentModificationException
  • 故障原因
    • 并发修改导致的异常
  • 解决方案
  1. List<Integer> list = Collections.synchronizedList(new ArrayList<>());//synchronized方法
  2. List<Integer> list = new CopyOnWriteArrayList<Integer>();//读写分离,写时复制,lock
  3. List<Integer> list = new Vector<Integer>();//synchronized方法
  • 优化建议
    • 在读多写少的时候推荐使用 CopyOnWriteArrayList 这个类

2 我们知道 HashSet 线程不安全,请编写一个不安全的案例并给出解决方案?

  • 故障现象
  1. public class UnsafeSetDemo {
  2. public static void main(String[] args) {
  3. Set<Integer> set = new HashSet<Integer>();
  4. Random random = new Random();
  5. ExecutorService executorService = Executors.newFixedThreadPool(7);
  6. for(int i = 0; i < 20; i++) {
  7. executorService.execute(()->{
  8. set.add(random.nextInt(10));
  9. System.out.println(set);
  10. });
  11. }
  12. }
  13. }
  • 发现报 java.util.ConcurrentModificationException
  • 故障原因
    • 并发修改导致的异常
  • 解决方案
  1. Set<Integer> set = Collections.synchronizedSet(new HashSet<>());//synchronized方法
  2. Set<Integer> set = new CopyOnWriteArraySet<Integer>();//读写分离,写时复制,lock
  3. Set<Integer> set = new ConcurrentSkipListSet<Integer>();
  • 优化建议
    • 在读多写少的时候推荐使用 CopyOnWriteArraySet 这个类

3 我们知道 HashMap 线程不安全,请编写一个不安全的案例并给出解决方案?

  • 故障现象
  1. public class UnsafeMapDemo {
  2. public static void main(String[] args) {
  3. Map<Integer, Integer> map = new HashMap<>();
  4. Random random = new Random();
  5. ExecutorService executorService = Executors.newFixedThreadPool(7);
  6. for(int i = 0; i < 20; i++) {
  7. executorService.execute(()->{
  8. map.put(random.nextInt(10),random.nextInt(10));
  9. System.out.println(map);
  10. });
  11. }
  12. }
  13. }
  • 发现报 java.util.ConcurrentModificationException
  • 故障原因
    • 并发修改导致的异常
  • 解决方案
  1. Map<Integer, Integer> map = Collections.synchronizedMap(new HashMap<>());
  2. Map<Integer, Integer> map = new ConcurrentHashMap<Integer, Integer>();
  3. Map<Integer, Integer> map = new ConcurrentSkipListMap<Integer, Integer>();
  • 优化建议
    • 在高并发情况下推荐使用 ConcurrentHashMap 这个类