java - 如何将带参数的方法传递给Callable
问题描述
我正在尝试在我的 Raytracer 中使用 Callable/Future 实现多线程,方法是按每行/列拆分进程。为此,我需要将变量从我的 Main 传递给 Callable,它不接受参数。
我尝试将整个函数作为可调用传递
这是我试图多线程的函数,'formen' 是我传递的对象组。发送光线和寻找交叉点是最需要计算能力的——
static Image raytrace(Camera camera, Group formen, int samples){
Image image = new Image(camera.width, camera.height);
for (int x = 0; x != camera.width; x++) {
for (int y = 0; y != camera.height; y++) {
Vec3 color = new Vec3(0, 0, 0);
for (int xi = 0; xi < samples; xi++) {
for (int yi = 0; yi < samples; yi++) {
double rx = random.nextDouble();
double ry = random.nextDouble();
double xs = x + (xi + rx) / samples;
double ys = y + (yi + ry) / samples;
Ray ray = camera.sendRay(xs,ys);
Hit hit = formen.intersect(ray);
if(hit != null) color = Vec3.add(color, calculateRadiance(formen, ray, 100));
}
}
color = Vec3.divide(color, Math.pow(samples, 2));
image.setPixel(x, y, color);
}
}
return image;
}
这是我的跟踪功能的样子:
int cores = Runtime.getRuntime().availableProcessors();
Thread[] threads = new Thread[cores];
Image[] images = new Image[cores];
// Pool creation
ExecutorService pool = Executors.newFixedThreadPool(4);
//images[core] = raytrace(camera, scene, nn);
for(int i = 0; i < camera.height; i++){
Future<Image> pixel = pool.submit(calculateOneRow);
//threads[i].start();
System.out.println("Thread started:");
pool.shutdown();
try {
System.out.println("Image written");
return pixel.get();
//Image color = pixel.get();
} catch (ExecutionException e) {
e.printStackTrace();
}
final long duration = (System.nanoTime() - startTime) / 1000000;
return image;
}
认为内部 for 循环必须进入我的 Callable 但我不知道如何将它们作为单独的任务传递。我的目标是减少渲染时间。
解决方案
推荐阅读
- jquery - 启用 CORS 访问 AWS API Gateway?
- python - 用于时间序列预测的 LSTM 中特定时期后的嘈杂火车损失(Keras)
- google-chrome-extension - 如何在 Microsoft Chromium Edge 中预安装 Chrome 扩展程序?
- javascript - 在 ECharts 中使用 Zurb Foundation 时遇到问题
- java - 应用程序编译时出现springboot错误
- c# - 如何在集成测试中绕过表单发布上的防伪令牌验证
- javascript - 如何在 React Native 中的特定元素的 FlatList 中呈现函数
- java - Java - 创建一个返回偏导数的方法
- r - 当我在 R 中绘制两个“y”轴时,是否有一个 ggplot2 表格可以“反转”一个轴(geom_bar())
- shell - 将序列号作为序列添加到 UNIX 中特定位置的文件中的每一行