码迷,mamicode.com
首页 > 编程语言 > 详细

hello java fork/join for java

时间:2014-12-02 15:21:21      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:io   ar   java   for   on   art   ef   as   new   

1,示例


import java.util.concurrent.RecursiveTask;

public class Calculator extends RecursiveTask<Integer> {  
	  
    private static final int THRESHOLD = 4;  
    private int start;  
    private int end;  
  
    public Calculator(int start, int end) {  
        this.start = start;  
        this.end = end;  
    }  
  
    @Override  
    protected Integer compute() {  
        int sum = 0;  
        if((end-start) < THRESHOLD){  
            for(int i = start; i<= end;i++){  
                sum += i;  
            }
            System.err.println(">>>>>>>>");
        }else{  
            int middle = (start + end) /2;  
            Calculator left = new Calculator(start, middle);  
            Calculator right = new Calculator(middle + 1, end);  
            left.fork();  
            right.fork();  
  
            sum = left.join() + right.join();  
        }  
        return sum;  
    }  
  
}  

2 运行

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

public class Test {

	/**
	 * @param args
	 * @throws Exception 
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException, Exception {
		// TODO Auto-generated method stub
		ForkJoinPool forkJoinPool = new ForkJoinPool();
		Future<Integer> result = forkJoinPool.submit(new Calculator(0, 9));

		//new Integer(49995000)
		System.err.println(result.get()); 


hello java fork/join for java

标签:io   ar   java   for   on   art   ef   as   new   

原文地址:http://blog.csdn.net/joeyon1985/article/details/41677947

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!