我目前正在编写一个小网络的东西,并希望cicle扔掉我的所有玩家,所以我使用了ArrayLists和Lists但是有很多Exception,所以深入到问题我用迭代器替换它们但是我得到并发修改所有“it.next()”中的异常:/。 所以如果请你能帮助我理解这个问题:)。
@Override
public void run()
{
StringBuilder l = new StringBuilder();
Iterator<UUID> pc;
Iterator<Packet> pa;
while (Jelly.isSTATUS()) {
pc = Jelly.getOnlinePlayers().keySet().iterator();
while (pc.hasNext())
try {
System.out.println("ENTERED!");
Player p = Jelly.getOnlinePlayers().get(pc.next());
System.out.println(p.getIGN());
if (Packetsts.containsKey(p) && !Packetsts.get(p).isEmpty())
try {
pa = Packetsts.get(p).iterator();
while(pa.hasNext()) {
Packet i = pa.next();
for ( String j : i.getData())
l.append(j + ",");
l.append("es");
System.out.println("Data: " + l.toString());
byte[] toSendBytes = l.toString().getBytes();
int toSendLen = toSendBytes.length;
byte[] toSendLenBytes = new byte[4];
toSendLenBytes[0] = (byte)(toSendLen & 0xff);
toSendLenBytes[1] = (byte)(toSendLen >> 8 & 0xff);
toSendLenBytes[2] = (byte)(toSendLen >> 16 & 0xff);
toSendLenBytes[3] = (byte)(toSendLen >> 24 & 0xff);
PrintStreams.get(p).write(toSendLenBytes);
PrintStreams.get(p).write(toSendBytes);
Packetsts.get(p).remove(i);
l.setLength(0);
}
} catch ( Exception ex) { }
} catch (ConcurrentModificationException ex){ ex.printStackTrace(); }
}
System.out.println("END!");
}
谢谢:)
更新:
@Override
public void run()
{
StringBuilder l = new StringBuilder();
Iterator<UUID> pc = Jelly.getOnlinePlayers().keySet().iterator();
Iterator<Packet> pa;
while (Jelly.isSTATUS())
if (!Jelly.getOnlinePlayers().keySet().isEmpty()) {
pc = Jelly.getOnlinePlayers().keySet().iterator();
while (pc.hasNext()) {
UUID u = pc.next();
Player p = Jelly.getOnlinePlayers().get(u);
if (Packetsts.containsKey(p) && !Packetsts.get(p).isEmpty())
try {
pa = Packetsts.get(p).iterator();
while(pa.hasNext()) {
Packet i = pa.next();
for ( String j : i.getData())
l.append(j + ",");
l.append("es");
System.out.println("Data: " + l.toString());
byte[] toSendBytes = l.toString().getBytes();
int toSendLen = toSendBytes.length;
byte[] toSendLenBytes = new byte[4];
toSendLenBytes[0] = (byte)(toSendLen & 0xff);
toSendLenBytes[1] = (byte)(toSendLen >> 8 & 0xff);
toSendLenBytes[2] = (byte)(toSendLen >> 16 & 0xff);
toSendLenBytes[3] = (byte)(toSendLen >> 24 & 0xff);
PrintStreams.get(p).write(toSendLenBytes);
PrintStreams.get(p).write(toSendBytes);
l = new StringBuilder();
}
Packetsts.get(p).clear();
} catch ( Exception ex) { ex.printStackTrace(); }
}
}
System.out.println("END!");
}
行“UUID u = pc.next();”拜托,我真的很讨厌并发修改异常:/
答案 0 :(得分:1)
这是不允许的
Packetsts.get(p).remove(i);
因为您正在迭代您尝试修改的ArrayList。如何在循环开始时复制它?删除元素后,您的最终目标是什么?