[英]Local variable i defined in an enclosing scope must be final or effectively final
[英]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.