ConcurrentModificationException

ConcurrentModificationException

This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
                                
                                    (24个答案)
                                
                        
                                2年前关闭。
            
                    
synchronized(queueClientList){
    Iterator<Client> iterator = queueClientList.iterator();
    while (iterator.hasNext()){
        Client client = new Client();
        client = iterator.next();
        try {
            Thread.sleep(client.serviceTime);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        System.out.println(client.ID+ " it`s out");
        queueClientList.remove(client);
    }
}


此代码应循环遍历queueClientList并使线程休眠client.serviceTime毫秒。唤醒后,应从queueClientList中删除​​当前客户端。

它给我ConcurrentModificationExceptionclient = iterator.next()

queueClientList的声明为:

public List<Client> queueClientList = Collections.synchronizedList(new ArrayList<Client>());


如果整个方法都同步,为什么会抛出该错误?

最佳答案

问题解决了。
问题是,我试图从列表中删除,同时反复进行,这是不可能的。

关于java - 遍历ArrayList时发生ConcurrentModificationException ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43157501/

10-11 20:31