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
原文地址:https://www.cnblogs.com/ssslinppp/p/8747252.html
时间: 2024-10-10 04:42:33