Java有支持并发修改的数据结构吗?
我正在用 Java 制作一个游戏。游戏中的每个敌人都是一个线程,它们不断循环游戏的数据结构(我总是使用 Vector 类)。
最近,我收到了“ConcurrentModificationException”,因为在线程循环遍历向量时,正在从向量中添加/删除元素。我知道有一些策略可以避免添加/删除问题(我实际上使用了一些策略来避免删除问题,但我仍然遇到“添加”问题)。
我听说java支持避免ConcurrentModificationException的Vector/List。
你知道这个结构可能是什么吗? 谢谢。
I'm making a game in Java. Every enemy in the game is a thread and they are constantly looping through the game's data structures (I always use the class Vector).
Lately I have been getting the "ConcurrentModificationException" because an element is being added/removed from a Vector while a Thread is looping through it. I know there are strategies to avoid the add/remove problem (I actually use some to avoid problems with Removes but I still have problems with "Adds").
I heard that java supports a Vector/List that avoids the ConcurrentModificationException.
Do you have any idea of what this structure might be?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看java.util.concurrent,它有你在寻找什么。
Check out java.util.concurrent, it has what you're looking for.
CopyOnWriteArrayList。但请仔细阅读其 javadocs,并考虑在实践中它是否提供了您所期望的行为(检查内存一致性效果),以及性能开销是否值得。除了与 ReentrantReadWriteLock 同步之外, AtomicReferences 和 Collections.synchronizedList 可能会帮助您。
CopyOnWriteArrayList. But read its javadocs carefully and consider if in practice it gives the behavior that you are expecting (check Memory Consistence effects), plus if the performance overhead is worth it. Besides synchronization with ReentrantReadWriteLock, AtomicReferences, and Collections.synchronizedList may help you.