【发布时间】:2016-12-01 07:39:17
【问题描述】:
我正在尝试在 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 异常。请提供有关如何拆分工作负载的建议(行与列与小网格。现在,我正在按行拆分)以及如何确定阈值。
【问题讨论】:
标签: java java-8 bufferedimage java.util.concurrent forkjoinpool