ForkJoin的RecursiveAction应用

129 篇文章 0 订阅

RecursiveAction的应用

//通用 divide-and-conquer 并行算法的伪代码。
                
// PSEUDOCODE
Result solve(Problem problem) { 
    if (problem.size < SEQUENTIAL_THRESHOLD)
        return solveSequentially(problem);
    else {
        Result left, right;
        INVOKE-IN-PARALLEL { 
            left = solve(extractLeftHalf(problem));
            right = solve(extractRightHalf(problem));
        }
        return combine(left, right);
    }
}

 

 我自己写了一个例子:

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;

/**
 * <pre>
 * @author kanpiaoxue
 * Date 2013-11-29
 * </pre>
 */
public class DivideAndConquer extends RecursiveAction {

	private static final long serialVersionUID = 5349972192067990608L;
	private final List<Integer> datas;
	private final int threshold;
	private int result;

	public DivideAndConquer(List<Integer> datas, int level) {
		super();
		this.datas = datas;
		this.threshold = level;
	}

	public static int sum(List<Integer> list) {
		int sum = 0;
		for (Integer i : list) {
			sum += i;
		}
		return sum;
	}

	@Override
	protected void compute() {
		System.out
				.println(Thread.currentThread().getName() + " start to work.");
		if (datas.size() < threshold) {
			result = sum(datas);
		} else {
			int toIndex = datas.size() / 2;
			DivideAndConquer left = new DivideAndConquer(datas.subList(0,
					toIndex), threshold);
			DivideAndConquer right = new DivideAndConquer(datas.subList(
					toIndex, datas.size()), threshold);
			invokeAll(left, right);
			result = Math.max(left.result, right.result);
		}
	}

	public int getResult() {
		return result;
	}

	private static List<Integer> createTestDatas(int count) {
		List<Integer> list = new ArrayList<Integer>();
		Random random = new Random();
		for (int i = 0; i < count; i++) {
			list.add(random.nextInt(1000));
		}
		return list;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int count = 100000;
		int level = count / 5;
		List<Integer> datas = createTestDatas(count);
		System.out.println("DivideAndConquer.main()");
		DivideAndConquer t = new DivideAndConquer(datas, level);
		ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime()
				.availableProcessors() * 4);
		long before = System.currentTimeMillis();
		pool.invoke(t);
		System.out.println("max:" + t.getResult() + ", it consumes "
				+ (System.currentTimeMillis() - before) + " ms.");
	}

}

 

更多的内容请参考:

http://www.ibm.com/developerworks/cn/java/j-lo-forkjoin/index.html

http://www.ibm.com/developerworks/cn/java/j-jtp11137.html

http://www.ibm.com/developerworks/cn/java/j-jtp03048.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值