迭代通过ArrayList时出现ConcurrentModificationException

时间:2017-04-01 13:29:26

标签: java

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删除当前客户端。

它为ConcurrentModificationException提供了client = iterator.next()

queueClientList的声明是:

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

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

1 个答案:

答案 0 :(得分:0)

问题解决了。 问题是,我试图从我的列表中删除,同时迭代它,这是不可能的。