这是我的课程,有两种方法可以修改 List 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()
用于线程 4,insert()
用于另一个线程(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)
它现在让我发疯!任何人都可以帮助找出错误吗?或者其他方法来做同样的事情?