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

问题描述

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

当我尝试进行 for 循环并根据 for 循环中的整数值 i 分配图像的坐标时,我收到一条错误消息:“我在封闭范围中定义的局部变量必须是最终的或有效的最终"

为什么会发生这种情况,我该如何解决

代码如下:

'''

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;
}

'''

解决方法

您需要一个 finali 的有效最终副本在循环内

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]);
            }
        }
    });
}

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