我正在尝试使用Java中的ForkJoinPool处理图像。我使用流对图像进行了一些自定义操作。我正在尝试将ForkJoinPool用于getRGB
和setRGB
方法。如何实现getRGB
方法的并行性?
@Override
public int[] getRGB(int xStart, int yStart, int w, int h, int[] rgbArray,int offset, int scansize) {
int[][] sol = new int[h][w];
int threshold = w;
class RecursiveSetter extends RecursiveAction {
int from;
int to;
FJBufferedImage image;
RecursiveSetter(int from, int to, FJBufferedImage image) {
this.from = from;
this.to = to;
this.image = image;
}
@Override
protected void compute() {
System.out.println("From : " + from + " To : " + to);
if (from >= to) return;
if (to - from == 1) {
computeDirectly(from);
return;
} else {
int mid = from + (to - from) / 2;
System.out.println("From : " + from + " To : " + to +
"Mid :" + mid);
invokeAll(
new RecursiveSetter(from, mid, image),
new RecursiveSetter(mid + 1, to, image));
return;
}
}
void computeDirectly(int row) {
sol[from] = image.getRealRGB(from, 0, w, 1, null, offset,
scansize);
}
}
ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors());
pool.invoke(new RecursiveSetter(0, h-1, this));
return Arrays.stream(sol)
.flatMapToInt(Arrays::stream)
.toArray();
}
的getRealRGB
方法的唯一代理BufferedImage
。我知道这可能不切实际,但我只想知道如何在这种情况下使用ForkJoinPool 。是的,上面的代码正在抛出ArrayIndexOutOfBound
异常。请就如何拆分工作负载(行与列与小网格。现在,我正在按行拆分)以及如何确定阈值提出建议。