分支合并框架

分支合并框架

复杂任务分拆给线程,大事化小,最后把拆分结果合并

原理

Fork and Join

相关类

ForkJoinPool 分支合并池
ForkJoinTesk 分支合并任务
RecursiveTask 递归任务
package main.java;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @author : syx
 * @date : 2021/7/7 11:02
 * @version :v1.0
 */
public class ForJoi {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyTesk myTesk1 = new MyTesk(0,100);
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> task = forkJoinPool.submit(myTesk1);
        System.out.println(task.get());
    }
}
//从0加到100
class MyTesk extends RecursiveTask<Integer>{
    public static final int ADJUST_VALUE = 10;
    private int begin;
    private int end;
    private int result;

    public MyTesk(int begin, int end) {
        this.begin = begin;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        if ((end-begin)<=ADJUST_VALUE){
            for (int i = begin; i <=end; i++) {
                result = result+i;
            }
        }else{
            int mid = (begin+end)/2;
            MyTesk myTesk1 = new MyTesk(begin,mid);
            MyTesk myTesk2 = new MyTesk(mid+1,end);
            myTesk1.fork();
            myTesk2.fork();
            result = myTesk1.join()+myTesk2.join();
        }
        return result;
    }
}
posted @ 2021-07-07 11:18  锤子布  阅读(64)  评论(0编辑  收藏  举报