gpt4 book ai didi

java - 向所有客户端发送消息时出现 ConcurrentModificationException

转载 作者:行者123 更新时间:2023-12-01 12:11:25 25 4
gpt4 key购买 nike

我在迭代套接字的 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();
}
}
}
}
}
}

最佳答案

这个问题的解决方案就是使用synchronizedList。它会自动处理线程之间的同步。

关于java - 向所有客户端发送消息时出现 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27251567/

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