您的位置:首页 > 编程语言 > Java开发

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

2016-01-12 18:25 561 查看
任务类:

@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个左右。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: