我正在尝试并行化我目前正在为大学工作的 raytracer,但我似乎无法让它工作。我尝试了多种实现,但问题仍然存在。渲染在几毫秒后停止,最多渲染了一小块图片。
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() 方法,它工作得很好,但由于它包含大部分计算,所以这不是一个选项。
最佳答案
如解释here ,您想调用 shutdown
告诉 Exector 在所有当前排队的任务 完成后关闭,然后调用 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);
关于Java - 多线程 Raytracer 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20442128/