`
fanger0914
  • 浏览: 1126 次
  • 性别: Icon_minigender_1
  • 来自: 西安
最近访客 更多访客>>
社区版块
存档分类
最新评论

学习java7的fork/join

阅读更多
在网上看到一个列子,顺便敲了一边,练练手

* ForkJoinPool是一个Excutor的子类
* ForkJoinTask:我们要使用ForkJoin框架,必须首先创建一个ForkJoin任务。它提供在任务中执行fork()和join()操作的机制,通常情况下我们不需要直接继承ForkJoinTask类,而只需要继承它的子类,Fork/Join框架提供了以下两个子类:
RecursiveAction:用于没有返回结果的任务。
RecursiveTask :用于有返回结果的任务。

class CountTask extends RecursiveTask<Integer>{
    private int THRESHOLD = 2;
    private int start ;
    private int end;

    CountTask(int start,int end){
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        boolean canFork = end-start>THRESHOLD;
        if(!canFork){
            for(int i=start;i<=end;i++){
                sum += i;
            }
        }else{
            int middle = (end-start)/2;
            CountTask task1 = new CountTask(start,middle);
            CountTask task2 = new CountTask(middle+1,end);
            task1.fork();
            task2.fork();
            sum = task1.join() + task1.join();
            /**
             * getException方法返回Throwable对象,
             * 如果任务被取消了则返回CancellationException。
             * 如果任务没有完成或者没有抛出异常则返回null
             */
            if(task1.isCompletedAbnormally())
            {
                System.out.println(task1.getException());
            }
            if(task2.isCompletedAbnormally())
            {
                System.out.println(task2.getException());
            }
        }
        return sum;
    }

    public static void main(String[] args){
        CountTask task = new CountTask(1,10000);
        ForkJoinPool pool = new ForkJoinPool();
        Future<Integer> sum = pool.submit(task);
        println(sum.get());
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics