package forkjoin;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import cputils.AbstractLinkAndData;
public class DataLinkForkJoin extends RecursiveTask<List<String>> {
private static final long serialVersionUID = -4046194613023076351L;
private static final int THRESHOLD = 20;
private int start;
private int end;
private AbstractLinkAndData service;
public DataLinkForkJoin(int start, int end,AbstractLinkAndData service) {
this.start = start;
this.end = end;
this.service = service;
}
@Override
protected List<String> compute() {
List<String> alllist = new ArrayList<String>();
List<String> list = null;
if ((end - start) < THRESHOLD) {
for (int i = start; i <= end; i++) {
list = service.dataLinks(i);
alllist.addAll(list);
}
return alllist;
}
int middle = (start + end) / 2;
DataLinkForkJoin left = new DataLinkForkJoin(start, middle,service);
DataLinkForkJoin right = new DataLinkForkJoin(middle + 1, end,service);
left.fork();
right.fork();
alllist.addAll(left.join());
alllist.addAll(right.join());
return alllist;
}
public static void main(String[] args) throws InterruptedException,
ExecutionException {
List<String> alllist = new ArrayList<String>();
long b = System.currentTimeMillis();
// alllist = wyService.wyDataLinks("2014043", 3);
// System.out.println("顺序执行:size:"+alllist.size()+"time:"+(System.currentTimeMillis()-b));
// for (int i = 0; i < 5; i++) {
b = System.currentTimeMillis();
ForkJoinPool forkJoinPool = new ForkJoinPool(Runtime.getRuntime()
.availableProcessors());
// int linkPages = wyService.dataLinkPages("2014043", 3);
// DataLinkForkJoin thread = new DataLinkForkJoin(1,linkPages);
// Future<List<String>> result = forkJoinPool.submit(thread);
// forkJoinPool.shutdown();
// System.out.println("ForkJoin:size:"+result.get().size()+" time:"+(System.currentTimeMillis()-b));
// }
}
}