迭代套接字的ArrayList时遇到问题。列表的目的是在除了最后一个连接之外的另一个客户端连接时向所有客户端发送消息。我得到ConcurrentModificationException,我不知道如何管理它。请帮忙!
服务器程序:
public void start() {
try {
serverSocket = new ServerSocket(10001);
thread = new Thread(new MessageClient(listOfClients));
thread.start();
while (!isStopped) {
socket = serverSocket.accept();
listOfClients.add(socket);
synchronized (listOfClients) {
listOfClients.notifyAll();
}
g.getTextArea().append(
"Client number " + listOfClients.size()
+ " has connected.\n");
threadClient = new Thread(new SerThread(socket, listOfClients));
threadClient.start();
}
} catch (IOException e) {
}
}
线程程序(MessageClient):
public void run() {
while (true) {
for (Iterator<Socket> cl = listOfClients.iterator(); cl.hasNext();) {
synchronized (listOfClients) {
cur = cl.next();
if (!cur.equals(listOfClients.get(listOfClients.size() - 1))) {
try {
System.out.println("dddddddd");
ous = new PrintWriter(cur.getOutputStream());
ous.println("Client " + listOfClients.size()
+ " has connected.");
ous.flush();
} catch (IOException e) {
JOptionPane
.showMessageDialog(null,
"There was a problem getting your outputstream.");
}
try {
System.out.println("ddd");
listOfClients.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
答案 0 :(得分:1)
此问题的解决方案只是使用synchronizedList
。它会自动处理线程之间的同步。
答案 1 :(得分:0)
您尝试在一个线程(在服务器中)修改集合listOfClients.add(socket)
,而另一个线程MessageClient
正在迭代它。