ArrayList不安全案例!以及3种解决方案!!

    public static void main(String[] args) {
       

        //1.   List list = new Vector<>();
        //2.   List list = Collections.synchronizedList(new ArrayList<>());
        //3.   List list = new CopyOnWriteArrayList<>();

	List list = new ArrayList();

       for (int i = 1; i <= 30; i++) {
           new Thread(() ->
            {
               list.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(list);

           }, String.valueOf(i)).start();
       }
    }
}

/**

  • 1.出现故障 : Exception in thread "14"java.util.ConcurrentModificationException

  • 2.导致原因 : 并发争抢修改导致 *

  • 3.解决方案 //1. List list = new Vector<>();
    //2. List list = Collections.synchronizedList(new ArrayList<>());
    //3. List list = new CopyOnWriteArrayList<>();写时复制 , 读写分离原则,读和写不同的容器

    **/

你可能感兴趣的:(ArrayList不安全案例!以及3种解决方案!!)