我嘗試處理使用Java中的一個ForkJoinPool的圖像。我使用流在圖像上執行一些自定義操作。我試圖用ForkJoinPool爲getRGB
和setRGB
方法。如何在getRGB
方法上實現並行性?ForkJoinPool BufferedImage的處理方式
@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
異常。請給出關於如何分割工作量的建議(行與列與小格,現在我正在分割),以及如何確定閾值。