微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我正在尝试使用多个线程通过我所谓的 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]);
            }
        }
    });
}

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。