最近学习Java Concurrent并发包下面的部分东西,国外 Doug Lea大神写的。
在技术群共享里找了一份资料,看的是阿里巴巴里温绍锦老师的《Java并发程序设计教程》这个PPT,下面代码我也是按照教程敲出来的
里面有讲到Fork/Join,也是Java7才有的,个人理解就是将一件大事情分解成N个线程去处理,然后合并线程处理结果。
不知道是不是MapReduce模型很像,MapReduce还没有了解很多,后续去学习一哈。下面是将一个大型数组排序。
import java.util.Arrays;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
public class ForkPractice {
public static void main(String[] args) {
ForkJoinPool mainPool = new ForkJoinPool();
int len = 1000*1000*10;
int[] array = new int[len];
mainPool.invoke(new SortTask(array, 0, len-1));
}
public static class SortTask extends RecursiveAction{
private int[] array;
private int fromIndex;
private int toIndex;
private final int chunksize= 1024;
public SortTask(int[] array, int fromIndex, int toIndex) {
this.array = array;
this.fromIndex = fromIndex;
this.toIndex = toIndex;
}
@Override
protected void compute() {
int size = toIndex-fromIndex+1;
if(size<chunksize){
Arrays.sort(array,fromIndex,toIndex);
}else{
int leftSize =size/2;
SortTask leftTask = new SortTask(array, fromIndex, fromIndex+leftSize);
SortTask rightTask =new SortTask(array,fromIndex+leftSize+1,toIndex);
this.invokeAll(leftTask,rightTask);
}
}
}
}