Why does ArrayList not throw ConcurrentModificationException when modified from multiple threads?

后端 未结 5 1463
被撕碎了的回忆
被撕碎了的回忆 2021-01-14 03:38

ConcurrentModificationException : This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.<

5条回答
  •  花落未央
    2021-01-14 04:23

    The reason you are not receiving a ConcurrentModificationException is that ArrayList.remove does not throw one. You can probably get one by starting an additional thread that iterates through the array:

    final List tickets = new ArrayList(100000);
    for (int i = 0; i < 100000; i++) {
        tickets.add("ticket NO," + i);
    }
    for (int i = 0; i < 10; i++) {
        Thread salethread = new Thread() {
            public void run() {
                while (tickets.size() > 0) {
                    tickets.remove(0);
                    System.out.println(Thread.currentThread().getId()+"Remove 0");
                }
            }
        };
        salethread.start();
    }
    new Thread() {
        public void run() {
            int totalLength = 0;
            for (String s : tickets) {
                totalLength += s.length();
            }
        }
    }.start();
    

提交回复
热议问题