简体   繁体   中英

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

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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