【Java并发编程实战】Fork-Join

1. Fibonacci

public class Fibonacci extends RecursiveTask<Integer> {

    int n;

    public Fibonacci(int n) {
        this.n = n;
    }

    @Override
    protected Integer compute() {
        if (n <= 1) {
            return n;
        }
        Fibonacci f1 = new Fibonacci(n - 1);
        f1.fork();
        Fibonacci f2 = new Fibonacci(n - 2);
        return f2.compute() + f1.join();
    }
}
@Test
    public void testFibonacci() {
        ForkJoinPool forkJoinPool = new ForkJoinPool(4);
        Fibonacci fibonacci = new Fibonacci(3);
        Assert.assertEquals(forkJoinPool.invoke(fibonacci).longValue(), 2);
    }

2. MR

public class MR extends RecursiveTask<Map<String, Long>> {
    private String[] fc;
    private int start, end;

    public MR(String[] fc, int start, int end) {
        this.fc = fc;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Map<String, Long> compute() {
        if (end - start == 1) {
            return calc(fc[start]);
        }
        int mid = (start + end) / 2;
        MR mr1 = new MR(fc, start, mid);
        mr1.fork();
        MR mr2 = new MR(fc, mid, end);

        return merge(mr2.compute(), mr1.join());
    }

    private Map<String, Long> merge(Map<String, Long> r1, Map<String, Long> r2){
        Map<String, Long> result = new HashMap<>();
        result.putAll(r1);
        r2.forEach((k,v) -> {
            Long c = result.get(k);
            if (c != null) {
                result.put(k, c+v);
            } else {
                result.put(k, v);
            }
        });
        return result;
    }

    private Map<String, Long> calc(String line) {

        Map<String, Long> result = new HashMap<>();
        String[] words = line.split("\\s+");
        for (String  w : words) {
            result.put(w, result.getOrDefault(w,0L) + 1);
        }
        return result;
    }
}
 @Test
    public void testWordCount() {
        ForkJoinPool forkJoinPool = new ForkJoinPool(4);
        String[] fc = {"hello world",
                "hello me",
                "hello fork",
                "hello join",
                "fork join in world"};
        MR mr = new MR(fc, 0, fc.length);
        Map<String, Long> result = forkJoinPool.invoke(mr);
        result.forEach((k,v) ->{
            System.out.println(k + ":" + v);
        });
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值