fork/joinjava并发编程-fork/join示例

Posted ssslinppp

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了fork/joinjava并发编程-fork/join示例相关的知识,希望对你有一定的参考价值。

package com.chinamobile.epic.tako.common.graphite.query.sync.impl;

import com.google.common.collect.Lists;

import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;

public class GraphiteQueryTask extends RecursiveTask<List<String>> {
    private List<String> uuids;

    private int THRESHOLD = 12;

    public GraphiteQueryTask(List<String> uuids) {
        this.uuids = uuids;
    }

    public static void main(String[] args) {
        ForkJoinPool pool = ForkJoinPool.commonPool();

        List<String> uuids = Lists.newArrayList();
        for (int i = 0; i < 40; i++) {
            uuids.add("uuid-" + i);
        }

        List<String> result = pool.invoke(new GraphiteQueryTask(uuids));
        System.out.println("========== 结果 ============");
        System.out.println(result);

    }

    @Override
    protected List<String> compute() {
        List<String> result = Lists.newArrayList();
        List<GraphiteQueryTask> forks = Lists.newArrayList();

        if (uuids.size() > THRESHOLD) {
            int mid = uuids.size() >>> 1;
            GraphiteQueryTask firstTask = new GraphiteQueryTask(Lists.newArrayList(uuids.subList(0, mid)));
            GraphiteQueryTask secondTask = new GraphiteQueryTask(Lists.newArrayList(uuids.subList(mid, uuids.size())));
            forks.add(firstTask);
            forks.add(secondTask);
            ForkJoinTask.invokeAll(forks);
        } else {
            result.add(postGraphite(uuids));
        }

        for (RecursiveTask<List<String>> task : forks) {
            result.addAll(task.join());
        }

        return result;
    }

    private String postGraphite(List<String> uuids) {
        System.out.println("============>ThreadId: [" + Thread.currentThread().getId() + "] , uuids.size:[" + uuids.size() + "]");
        System.out.println(uuids);

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "@@@-" + Thread.currentThread().getId() + "-" + uuids.size();
    }
}

http://www.baeldung.com/java-fork-join

以上是关于fork/joinjava并发编程-fork/join示例的主要内容,如果未能解决你的问题,请参考以下文章

java并行之parallerlStream

Go语言学习之旅--并发编程

Go语言学习之旅--并发编程

Go语言学习之旅--并发编程

并发编程路线

java并发编程看啥书比较好