繁体   English   中英

如何解决错误:“我在封闭 scope 中定义的局部变量必须是最终的或有效的最终”?

[英]How can I work around the error: “Local variable i defined in an enclosing scope must be final or effectively final”?

我正在尝试使用多个线程通过我所谓的方法 filterImageParallel() 过滤图像的像素。

当我尝试创建一个 for 循环并根据 for 循环中的 integer 值 i 分配图像的坐标时,我收到一条错误消息:“我在封闭的 scope 中定义的局部变量必须是最终的或有效的最终”

为什么会发生,我该如何解决?

这是代码:

'''

public static double[][] filterImageParallel(double[][] pixels, int width, int height, DoubleUnaryOperator filter, int numThreads) {
    
    ExecutorService tp = Executors.newCachedThreadPool();
    
    double[][] result = new double[width][height];
    int newWidth = width / numThreads;
    
    for (int i = 0; i < numThreads; i++) {
        tp.submit(() -> {
            for (int x = i * newWidth; x < (i * newWidth) + newWidth; x++) {
                for (int y = 0; y < height; y++) {
                    result[x][y] = filter.applyAsDouble(pixels[x][y]);
                }
            }
        });
    }
    return result;
}

'''

您需要i在循环内的final或有效最终副本

for (int i = 0; i < numThreads; i++) {
    int threadIndex = i;
    tp.submit(() -> {
        for (int x = threadIndex * newWidth; x < (threadIndex * newWidth) + newWidth; x++) {
            for (int y = 0; y < height; y++) {
                result[x][y] = filter.applyAsDouble(pixels[x][y]);
            }
        }
    });
}

但请注意,如果图像的宽度不能被线程数整除,您的代码可能无法正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM