如果只有一个线程正在写入它在Java中的Synconisized List / Map [英] Synconisized List/Map in Java if only one thread is writing to it
问题描述
第一个线程是用对象连续填充一个集合。第二个线程需要遍历这些对象,但它不会改变集合。
The first thread is filling a collection continuously with objects. A second thread needs to iterate over these objects, but it will not change the collection.
目前我使用Collection.synchronized ...使它线程安全,但是有很快的方法吗?
Currently I use Collection.synchronized... for making it thread-safe but is there a fast way to doing it?
很抱歉,没有给出我的上下文的一些信息:
Sorry for not giving some information about my context:
:第一个线程(ui)连续地将鼠标位置写入ArrayList,只要按下鼠标按钮。第二个线程(render)根据列表绘制一行。
It's simple: The first thread (ui) continuously writes the mouse position to the ArrayList, as long as the mousebutton is pressed down. The second thread (render) draws a line based on the list.
推荐答案
即使你同步列表, -safe同时迭代它,所以请确保你同步它:
Even if you synchronize the list, it's not necessarily thread-safe while iterating over it, so make sure you synchronize on it:
synchronized(synchronizedList) {
for (Object o : synchronizedList) {
doSomething()
}
}
< h3>编辑:
这是一篇很清楚的文章:
http://java67.blogspot.com/2014/12/how-to-synchronize-arraylist-in-java.html
这篇关于如果只有一个线程正在写入它在Java中的Synconisized List / Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!