gpt4 book ai didi

java - 运行两个线程时出现 ConcurrentModificationException 问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:19:24 25 4
gpt4 key购买 nike

所以,我目前正在一个支持多客户端的服务器上工作,我有一个线程检查是否有任何套接字连接到给定端口,然后将它们添加到另一个线程用来更新我的所有内容的数组列表需要处理客户端(更新信息、检查 DataInputStream、通过服务器发送文本)等。

客户端代码:

public class Loop implements Runnable{

ArrayList<ClientInstance> clientsConnected = new ArrayList<ClientInstance>();

@Override
public void run() {
while(true) {
checkInputStream();
}

}

public void checkInputStream() {
for (ClientInstance s : clientsConnected) {
s.checkInputStream();
}
}

服务器代码:

public synchronized void waitForClient() {
try {
System.out.println("Waiting for client on port: "
+ serverSocket.getLocalPort());
Socket client = serverSocket.accept();
System.out.println("Client Connected! " + client.getInetAddress());
loop.getClientsConnected().add(new ClientInstance(client));
System.out.println("Client added to clients connected! ");
} catch (IOException e) {
e.printStackTrace();
}
}

但是当我运行服务器然后将一个客户端连接到它时它工作正常,但是当我连接另一个客户端时它给了我这个问题:

Exception in thread "Thread-1" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)

我该怎么办?

最佳答案

这是因为您正在修改数组列表(即在 waitForClient() 方法中的列表中添加元素),同时您在 checkInputStream() 方法中对其进行迭代.

如@Arjit 所述,使用 CopyOnWriteArrayList而不是 ArrayList

关于java - 运行两个线程时出现 ConcurrentModificationException 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30634872/

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