简体   繁体   English

简单的Java并发问题

[英]Simple Java Concurrency Issue

I have a class that extends JPanel and draws ~10 images on screen by overriding the paint method (using this method as I want to be able to manipulate the images as I draw each one). 我有一个类,它扩展了JPanel并通过覆盖paint方法在屏幕上绘制了约10张图像(使用此方法是因为我希望能够在绘制每个图像时操纵图像)。 What I want to be able to do is have an update method in the class which I pass a list of potential image updates every frame. 我想要做的是在类中有一个update方法,我每帧传递一个潜在的图像更新列表。 Here is what I have 这是我所拥有的

List<BufferedImage> imageList = Collections.synchronizedList(new ArrayList());

public void update(list<String> imagePaths) {
    for (String path : imagePaths) {
        synchronized (imageList) {
            //Modify image list adding and removing buffered images
        }
    }
    repaint();
}

@Override
public void paintComponent(Graphics g) {
     synchronized (imageList) {
         g.drawImage(img, 0, 0, this);
     }
}

Currently as you can imagine it runs extremely slow due to the synchronized blocks? 正如您所能想象的那样,当前由于同步块而运行得非常慢? How can I drastically improve the performance please? 请问如何才能大大提高性能?

You're using a synchronized list, and then also synchronizing on that list when you iterate it. 您使用的是同步列表,然后又同步在名单 ,当你重复它。 You'll probably see better performance by using something like a CopyOnWriteArrayList , which will always provide a consistent snapshot when iterated, and remove the synchronized blocks entirely. 通过使用诸如CopyOnWriteArrayList类的东西,您可能会看到更好的性能,该对象在迭代时将始终提供一致的快照,并完全删除同步的块。

Although, looking at your snippet, it's not clear to me which list is being iterated -- you have imageList and imagePaths , and I'm not sure where the actual images are retrieved from the list. 尽管查看您的代码片段,但我不清楚正在迭代哪个列表-您具有imageListimagePaths ,而且我不确定从列表中检索实际图像的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM