java—如何解决错误:“我在封闭范围中定义的局部变量必须是final或实际上是final”?

zzoitvuj  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(303)

我正在尝试使用多个线程来过滤我所谓的filterimageparallel()方法的图像像素。
当我尝试做一个for循环,并根据for循环中的整数值i来分配图像的坐标时,我得到了一个错误:“我在封闭范围中定义的局部变量必须是final或实际上是final”
为什么会发生这种情况?我该如何应对?
代码如下:
'''

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

'''

mqxuamgl

mqxuamgl1#

你需要一个 final 或有效的最终副本 i 圈内

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

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

相关问题