访问 BufferedImage 线程安全
在 Java 中,我有 2 个线程,它们都访问(而不是修改)同一个 BufferedImage。我只是使用这样的代码将缓冲图像绘制到单独的 Graphics2D 对象中。
Graphics2D g = getGraphics();
g.drawImage(myImage, 0, 0, null);
我是否需要同步对图像的访问?
我知道 AWTEventThread 不是线程安全的等。我只是在后台线程中构建一些 BufferedImage。
非常感谢...
In Java, I have 2 threads that are both accessing (not modifying) the same BufferedImage. I'm simply drawing the buffered image into a separate Graphics2D objects with code like this.
Graphics2D g = getGraphics();
g.drawImage(myImage, 0, 0, null);
Is there any reason I need to synchronize access to the images?
I know about the AWTEventThread not being thread safe etc. I'm just building some BufferedImages in a background thread.
Thanks much...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(你的问题的标题实际上与正文中描述的场景并不匹配,所以我假设你正在询问这两种情况......)
这两个线程只是访问(此时)不变的
BufferedImage
不需要在它们之间进行同步。但是,首先创建并初始化 BufferedImage 对象的线程与随后读取该对象的任何线程之间确实需要存在“发生前”关系。如果没有该同步点,读取线程可能会看到部分图像数据结构的陈旧值。
(The title of your question doesn't actually match the scenario described in the body, so I'm assuming that you are asking about both cases ...)
The two threads that are just accessing an (at that point) non-changing
BufferedImage
would not need to synchronize between themselves.However, there does need to be a happens-before relationship between the thread that created and initialized the
BufferedImage
object in the first place and any threads that subsequently read it. Without that synchronization point, the reading threads might see stale values for parts of the image data structure.即使在另一个只读线程中,对 EDT 所做的更改也必须变得可见,并且这需要某种形式的同步来创建发生在关系。 此处显示了几种替代方案。
Even in another, read-only thread, changes made on the EDT must become visible, and that requires some form of synchronization to create a happens-before relation. Several alternatives are shown here.