JDK 7 中的 Fork/Join 模式 简单入门

任务类:

@SuppressWarnings("serial")
public class MyTask extends RecursiveTask<Integer> {
    List<Integer> i;
 
    public MyTask(List<Integer> list) {
        this.i = list;
    }
 
    @Override
    protected Integer compute() {
        int res = Integer.MIN_VALUE;
        if (i.size() > 2) {
            MyTask l = new MyTask(i.subList(0, i.size()/2) );
            MyTask r = new MyTask(i.subList(i.size()/2, i.size()));
            l.fork();
            r.fork();
            res = Math.max(l.join(), r.join());
        }else{
            if(i.size() == 2){
                System.out.println("compare " + i.get(0) + " and " + i.get(1));
                res = Math.max(i.get(0), i.get(1)) ;
                System.out.println("return "+res);
            }else{
                System.out.println("only one");
                res = i.get(0);
                System.out.println("return "+res);
            }
        }
        return res;
    }
 
}

启动任务:

public class MainTest {
    public static void main(String[] args) {
        ArrayList<Integer> l = new ArrayList<Integer>();
        for(int i=0;i<1000;i++){
            l.add((int)(Math.random() * 1000));
        }
        //System.out.println(l);
        MyTask mt = new MyTask(l);
 
        ForkJoinPool forkJoinPool = new ForkJoinPool();
 
        Future<Integer> result = forkJoinPool.submit(mt);
 
        try {
            System.out.println("max is " + result.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
 
        forkJoinPool.shutdown();
    }
}

实际过程中一个值得注意的地方:如果任务启动的线程数过多,会出现内存溢出:java.lang.OutOfMemoryError: unable to create new native thread。

默认jvm设置下,最多本地线程数只有2300个左右

经过简单的ivm参数设置-xss设为64k时线程数达到4630个左右。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值