目前,我正在开发一个支持多客户端的服务器,我有一个线程检查是否有任何套接字连接到给定的端口,然后将它们添加到一个arraylist中,另一个线程使用该arraylist来更新需要处理的客户端信息(更新信息、检查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)
我该怎么办?