ForkJoinPool-RecursiveTask简单实践

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);
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值