如果只有一个线程正在写入Java中的同步列表/映射 [英] Synchronized List/Map in Java if only one thread is writing to it

查看:91
本文介绍了如果只有一个线程正在写入Java中的同步列表/映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一个线程正在用对象连续填充集合。第二个线程需要遍历这些对象,但不会更改集合。

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?

很简单:只要按下鼠标按钮,第一个线程(ui)就会连续将鼠标位置写入ArrayList。第二个线程(渲染)根据列表绘制一条线。

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中的同步列表/映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆