1

我正在尝试绘制一个取消多个线程的三角形,每个线程将绘制三角形的一个独立部分。但它的运行速度比只使用一个线程要慢得多。有什么问题?

这是代码:

    (...)
int nCores = Runtime.getRuntime().availableProcessors();
    Thread[] threads = new Thread[nCores];
    int width = box[1][0] - box[0][0];
    int incr = width / nCores;
    int x = box[0][0];
    for (int i = 0; i < nCores; i++) {
        threads[i] = new Thread(new TriFiller(x, x + incr, z - nx * incr
                * i));
        threads[i].start();
        x += incr;
    }
    try {
        for (int i = 0; i < nCores; i++)    
            threads[i].join();
    } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

和可运行的:

public class TriFiller implements Runnable {
    int xi, xf;
    double z;

    public TriFiller(int xi, int xf, double z) {
        super();
        this.xi = xi;
        this.xf = xf;
        this.z = z;
    }

    @Override
    public void run() {
        boolean inOut = false;
        double z0 = z;
        int rgbColor = shade.getRGB();
        BufferedImage image = wd.getImage();
        for (int i = xi; i < xf; i++) {
            for (int j = box[0][1]; j < box[1][1]; j++) {
                if (isOnSet(i, j, polyNormals, intBuffer)
                        && z < zBuffer[i][j] && z > zd) {
                    image.setRGB(i, j, rgbColor);
                    zBuffer[i][j] = z;
                    inOut = true;
                } else {
                    if (inOut) {
                        break;
                    }
                }
                z += -ny;
            }
            z0 += -nx;
            z = z0;
            inOut = false;
        }
    }
}
4

1 回答 1

1

您遇到问题的原因是,摆动绘画不适用于多线程。阅读另一个论坛 (jfree.org)的摘录:

“我认为你没有看到任何性能改进的原因是你没有通过分离另一个线程来引入任何并行性。

在 Swing 中更新屏幕的方式本质上是:

1) 一旦组件决定在屏幕上重新绘制它,就会调用 JComponent.repaint()。这导致异步重绘请求被发送到 RepaintManager,RepaintManager 使用 invokeLater() 在 EDT 上对 Runnable 进行排队。

2)当Runnable执行时,它调用RepaintManager,它调用Component上的paintImmediately()。然后该组件设置剪辑矩形并调用paint(),最终调用您已覆盖的paintComponent()。请记住,屏幕已锁定并将保持锁定状态,直到组件完全重新绘制脏矩形。

关闭线程来生成图像缓冲区是没有意义的,因为 RepaintManager 必须阻塞直到缓冲区准备好,这样它才能在释放屏幕上的锁定之前完成更新脏矩形。

swing 支持的所有工具包(windows、linux、mac)都是单线程设计的。不能同时更新屏幕的多个区域。”

于 2014-01-31T23:53:45.010 回答