gpt4 book ai didi

java - 已同步,但出现 ConcurrentModificationException

转载 作者:行者123 更新时间:2023-11-29 10:15:24 29 4
gpt4 key购买 nike

<分区>

这是我的类,有两个方法修改列表 PacketQueue。这两个方法是在两个线程中执行的,所以标记了synchronize

public class MessageHandler implements nuctrl.interfaces.MessageHandler, Runnable {
private static final List<GatewayMsg> PacketQueue = new LinkedList<GatewayMsg>();

@Override
public void insert(GatewayMsg msg) {
synchronized (PacketQueue){
PacketQueue.add(msg);
PacketQueue.notify();
}
log.debug("insert " + msg.toString());
}

@Override
public void run() {
while(running){
synchronized (PacketQueue){
try {
while(PacketQueue.size() == 0){
PacketQueue.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
for (GatewayMsg msg : PacketQueue){
PacketQueue.remove(msg);
packetHandler.onPacket(msg);//method call
}
}
}
}
}

run() 用于 thread-4insert() 用于另一个线程(I/O Worker #1 )。 Synchronized 已添加,一切似乎都正常,但我仍然不断收到 ConcurrentModificationException。

DEBUG [New I/O worker #1] (MessageHandler.java:47)| insert GatewayMsg<>
Exception in thread "Thread-4" java.util.ConcurrentModificationException
at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:761)
at java.util.LinkedList$ListItr.next(LinkedList.java:696)
at nuctrl.core.MessageHandler.run(MessageHandler.java:67)
at java.lang.Thread.run(Thread.java:680)

这让我发疯了!任何人都可以帮助找出错误吗?或者用其他方法来做同样的事情?

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