首页 > 解决方案 > 如何将带参数的方法传递给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 但我不知道如何将它们作为单独的任务传递。我的目标是减少渲染时间。

标签: javamultithreadingfuturecallable

解决方案


推荐阅读