我正在学习Java的多线程技能,并使用java.util.concurrent.ForkJoinTask中的RecursiveTask实现了这种简单的分而治之方法,以在列表中查找max-element。
public static void main(String[] args){
new Multithreading().compute();
}
public void compute(){
Integer[] ints = {3,2,5,7,1};
List<Integer> list = Arrays.asList(ints);
ForkJoinPool pool = new ForkJoinPool();
Integer result = pool.invoke(new DividerTask(list));
System.out.println(result);
}
class DividerTask extends RecursiveTask<Integer>{
List<Integer> list;
public DividerTask(List list){
this.list = list;
}
@Override
protected Integer compute(){
if(list.size() > 2){
int mid = list.size()/2;
List<Integer> list1 = list.subList(0,mid);
List<Integer> list2 = list.subList(mid,list.size());
DividerTask dt1 = new DividerTask(list1);
dt1.fork();
DividerTask dt2 = new DividerTask(list2);
dt2.fork();
Integer res1 = dt1.join();
Integer res2 = dt2.join();
return (res1 > res2 ? res1 : res2);
}
if(list.size() == 2){
Integer res1 = list.get(0);
Integer res2 = list.get(1);
return (res1 > res2 ? res1 : res2);
}
return list.get(0);
}
}
您将如何处理?您还会考虑其他哪些多线程解决方案?
最佳答案
请遵循RecursiveTask中的示例:
dt1.fork()
return dt2.compute() + dt1.join()
您正在执行的double join()会导致两个计算都在等待。使用dt2.compute()强制当前线程继续移动。