public class ForkJoinTaskExample extends RecursiveTask<List<Integer>> {
private List<Long> channelIds;
public ForkJoinTaskExample(List<Long> channelIds){
this.channelIds=channelIds;
}
/**
* The main computation performed by this task.
*
* @return the result of the computation
*/
@Override
protected List<Integer> compute() {
boolean canCompute=channelIds.size()<=1;
List<Integer> resultList = new ArrayList<>();
if(canCompute){
resultList.add(channelIds.get(0).intValue());
}else {
int middle = 1;
if(channelIds.size()>=3){
middle = (channelIds.size()/2)+1;
}
List<List<Long>> partition = Lists.partition(channelIds, middle);
ForkJoinTaskExample leftTask = new ForkJoinTaskExample(partition.get(0));
ForkJoinTaskExample rightTask = new ForkJoinTaskExample(partition.get(1));
// 等待任务执行结束合并其结果
leftTask.fork();
rightTask.fork();
List<Integer> leftResult = leftTask.join();
List<Integer> rightResult = rightTask.join();
resultList.addAll(leftResult) ;
resultList.addAll(rightResult);
}
return resultList;
}
public static void main(String[] args) {
ForkJoinPool forkjoinPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors() -1);
List<Long> channelIds = new ArrayList<>();
channelIds.add(10L);
channelIds.add(11L);
channelIds.add(12L);
channelIds.add(13L);
channelIds.add(14L);
channelIds.add(15L);
channelIds.add(16L);
channelIds.add(17L);
ForkJoinTaskExample task = new ForkJoinTaskExample(channelIds);
ForkJoinTask<List<Integer>> submit = forkjoinPool.submit(task);
List<Integer> integerList = new ArrayList<>();
try {
integerList = submit.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
System.out.println(integerList);
}
}
ForkJoinPool-RecursiveTask简单实践
最新推荐文章于 2024-01-25 01:55:27 发布