简体   繁体   English

Java多线程 - 使用Fork-Join方法在列表中查找max-element

[英]Java multi-threading - Find max-element in list with a Fork-Join approach

I'm brushing up on my multi-threading skills in Java and implemented this simple divide&conquer approach to find the max-element in a list, using RecursiveTask from java.util.concurrent.ForkJoinTask 我正在研究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);
    }
}

How would you approach this? 你会怎么做? What other multi-threaded solutions would you consider? 您会考虑哪些其他多线程解决方案?

Follow the example in RecursiveTask: 按照RecursiveTask中的示例进行操作:

dt1.fork()
return dt2.compute() + dt1.join()

The double join() you are doing results in both computes waiting. 你正在做的双连接()会导致两个计算器等待。 Use the dt2.compute() to force the current thread to keep moving. 使用dt2.compute()强制当前线程继续移动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM