gpt4 book ai didi

遍历 arraylist 时抛出 java.util.ConcurrentModificationException

转载 作者:行者123 更新时间:2023-12-01 13:30:16 24 4
gpt4 key购买 nike

        if (IOThread.getInstance().clientsToAdd.size() > 0) {
for (Client client : IOThread.getInstance().clientsToAdd) {
clients.add(client);
IOThread.getInstance().removeAddedClient(client);
}
}

当它在我的主循环中运行时,我会抛出此错误:

    [DEBUG]: Added new connection: 79.142.74.45
Exception in thread "Thread-0" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at Server.run(Server.java:35)
at java.lang.Thread.run(Thread.java:744)

此方法抛出错误:

    public void removeClient(Client client) {
Iterator<Client> clientIterator = clients.iterator();
while (clientIterator.hasNext()) {
Client currentClient = clientIterator.next();
if (client.equals(currentClient)) {
clientIterator.remove();
}
}
}

最佳答案

此行导致错误:

IOThread.getInstance().removeAddedClient(client);

您在循环访问客户端时正在删除它。请改用 iterator.remove() 。

关于遍历 arraylist 时抛出 java.util.ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21609609/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com