Java - 多线程Raytracer循环

时间:2013-12-07 13:50:16

标签: java multithreading raytracing

我正在尝试并行化我目前正在为大学工作的光线跟踪器,但我似乎无法让它工作。我尝试了多个实现,但问题保持不变。渲染在几毫秒后停止,最多只渲染一小部分图片。

    final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    long start = System.currentTimeMillis();
    for (int i = 0; i < image.getWidth(); i++) {
        final int ii =i;
        executor.execute(new Runnable() {
            public void run() {
                for (int j = 0; j < image.getHeight(); j++) {
                    raster.setDataElements(ii, image.getHeight()-j-1, model.getDataElements(
                            getPixelColor(width,height,ii,j,world,pcameras2),0, null));
                }
            }
        });
    }
    g.drawImage(this.image, 0, 0, this);
    System.out.println("Rednering finished in: " + (System.currentTimeMillis()-start)/1000.0 + " seconds");
}
public static float[] getPixelColor(final int width,final int height,
        final int x,final int y,final World world,final Camera camera){
    final Hit hit = world.hit(camera.rayFor(width,height, x, y));
    if(hit != null){
        return new float[]{(float) hit.geo.material.ColorFor(hit,world).r,
                (float) hit.geo.material.ColorFor(hit,world).g,(float) hit.geo.material.ColorFor(hit,world).b, 1};
    } else {
        return new float[]{(float) world.backgroundColor.r, (float) world.backgroundColor.g, (float) world.backgroundColor.b, 1};
    }
}

我发现,如果我排除了world.hit()方法,它可以正常工作,但由于这包含大部分计算,这不是一个选项。

1 个答案:

答案 0 :(得分:0)

正如here所述,您希望调用shutdown告诉执行者在所有当前排队的任务完成后关闭,然后awaitTermination等到他们都完成了。

executor.shutdown();
try {
    executor.awaitTermination(100, TimeUnit.SECONDS);
}
catch (InterruptedException e) {
    // what should happen if timeout was hit
}

// image is complete here (if InterruptedException was not thrown)
g.drawImage(this.image, 0, 0, this);