• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

58 ForkJoin

开发技术 开发技术 2周前 (05-02) 7次浏览

ForkJoin

什么是ForkJoin

ForkJoin在JDK1.7 并发执行任务!提高效率,大数据量!

大数据:Map Reduce(把大任务拆分成小任务)
58 ForkJoin

ForkJoin特点:工作窃取

B线程执行完之后会去抢夺A线程的任务

这个里面维护的都是双端队列
58 ForkJoin

如果使用ForkJoinPool通过它来执行

  1. ForkJoinPool 通过它来执行

  2. 计算任务ForkJoinPool .execute(ForkJoinTask<?> task)
    58 ForkJoin

public class ForkJoinDemo extends RecursiveTask<Long> {

    private Long start;
    private Long end;

    //临界值
    private Long temp = 10000L;

    public ForkJoinDemo(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

//计算方法
    @Override
    protected Long compute() {
        if ((end - start) < temp){
            Long sum = 0L;
            for (long i = start; i < end; i++) {
                sum += i;
            }
            return sum;
        }else { //forkjoin 递归
            long middle = (start + end) / 2;
            ForkJoinDemo task1 = new ForkJoinDemo(start, middle);
            task1.fork();
            ForkJoinDemo task2 = new ForkJoinDemo(middle + 1, end);
            task1.fork();//拆分任务  把任务压入线程队列

            return task1.join() + task2.join();

        }
    }
}

public class Task {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test1();
    }
    public static void test1() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinDemo task = new ForkJoinDemo(0L, 10_0000L);
        ForkJoinTask<Long> submit = forkJoinPool.submit(task);
        Long sum = submit.get();

        long end = System.currentTimeMillis();
        System.out.println("sum=" + sum + "时间" + (end - start)) ;
    }
}


程序员灯塔
转载请注明原文链接:58 ForkJoin
喜欢 (0)