Java Fork/Join 例子

1 篇文章 0 订阅
1 篇文章 0 订阅

先引用<<Java 7 Concurrency Cookbook>>书中一段关于Fork Join的描述:

This framework is designed to solve problems that can be broken into smaller tasks using
the divide and conquer technique. Inside a task, you check the size of the problem you wantto resolve and, if it's bigger than an established size, you divide it in smaller tasks that are executed using the framework. If the size of the problem is smaller than the established size,you solve the problem directly in the task and then, optionally, it returns a 
result. The following diagram summarizes this concept:



描述很清楚,易懂。Fork 就是把任务划分, Join就是等所有的子任务都完成后执行的合并操作。

 

前提就是 所谓的任务要可以拆分,比如说有求10万个数字的和,可以改成2个5万数字求和的求和,再可以分成4个2.5万数字求和的求和的求和。

 

就拿求和做个例子(1-100求和):

 

package com.javaeye.demo;

import java.util.List;
import java.util.concurrent.RecursiveTask;

public class Task extends RecursiveTask<Integer>{

	private static final long serialVersionUID = 1L;
	
	private List<Integer> numberList;
	private int start;
	private int end;
	private int THRESHOLD = 10;
	
	public Task(List<Integer> numberList) {
		this.numberList = numberList;
		start = 0;
		end = this.numberList.size() - 1;
	}
	
	public Task(List<Integer> numberList, int start, int end) {
		this.numberList = numberList;
		this.start = start;
		this.end = end;
	}
	
	@Override
	protected Integer compute() {
		if (end - start <= THRESHOLD) {
			return sum();
		} else {
			int pivot = (end + start )/2;
			Task task1 = new Task(numberList, start, pivot);
			Task task2 = new Task(numberList, pivot+1, end);
			task1.fork();
			task2.fork();
			return 	task1.join() + task2.join();
		}
		
	}

	private Integer sum() {
		Integer sum = 0;
		for (int i = start;i <= end; i++) {
			sum += this.numberList.get(i);
		}
		return sum;
	}
}

 

package com.javaeye.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;

public class Main {

	public static void main(String[] args) throws Exception{
		ForkJoinPool pool = new ForkJoinPool();
		
		Task task = new Task(getData(100));
		Future<Integer> result = pool.submit(task);
		System.out.println(result.get());
	}
	
	private static List<Integer> getData(int len) {
		List<Integer> list = new ArrayList<Integer>();
		for (int i=1; i <= len; i++) {
			list.add(i);
		}
		return list;
	}

}

 
输出结果: 5050.

 

只为简单记录。
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值