没有 block if delay == 2
它可以工作,但不能与它一起工作。
这是 ForkJoin 的计算:
compute() {
if(lastElem - firstElem == 1)
return array[firstElem];
if(lastElem - firstElem == 2){
if(array[firstElem] > array[lastElem])
return array[firstElem];
else
return array[lastElem];
}
int midElem = (firstElem + lastElem) / 2;
MyForkJoinTask left = new MyForkJoinTask(array, firstElem, midElem);
MyForkJoinTask right = new MyForkJoinTask(array, midElem, lastElem);
left.fork();
right.fork();
int leftResult = left.join();
int rightResult = right.join();
if(leftResult > rightResult)
return leftResult;
else
return rightResult;
}
这是我的主要方法:
main(String[] args) {
Random r = new Random();
for(int i = 0; i < array.length; i++){
array[i] = r.nextInt();
}
MyForkJoinTask root = new MyForkJoinTask(array);
F_J_POOL.submit(root);
System.out.println("Result is " + root.join());
}
短错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
at com.bg.fork_join.MainFJ.main(MainFJ.java:24) Caused by: java.lang.ArrayIndexOutOfBoundsException ... 15 more
Caused by: java.lang.ArrayIndexOutOfBoundsException: 10000 at com.bg.fork_join.MyForkJoinTask.compute(MyForkJoinTask.java:31)
你能告诉我问题出在哪里吗?
最佳答案
我对ForkJoin
一无所知,但仅从一般原则来看这看起来很可疑:
if(lastElem - firstElem == 2){
if(array[firstElem] > array[lastElem])
return array[firstElem];
else
return array[lastElem];
}
代码的其余部分使您看起来正在处理从 firstElem
(包含)到 lastElem
(排除)的子数组,那么您不应该使用 lastElem-1
进行索引吗?
关于java - 使用 ForkJoin 查找最大数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22868431/