这是一个简单的ForkJoin示例程序,该程序将一个数组的内容求平方根。是通过RecursiveAction子类完成的。
注意:需要重写compute方法。
package ForkJoindemo;
import java.util.concurrent.RecursiveAction;
/**
* @author firethinks
*
*/
public class SqrtTransform extends RecursiveAction {
private final int seqThreshold = 1000;
//将要被转换的数组
double []data;
//分界点
int start,end;
SqrtTransform(double[] value,int start,int end){
this.data = value;
this.start = start;
this.end = end;
}
/* 重写compute方法
* @see java.util.concurrent.RecursiveAction#compute()
*/
@Override
protected void compute() {
if ((end - start) < seqThreshold) {
for (int i =start; i < end; i++) {
data[i] = Math.sqrt(data[i]);
}
}else{
int middlle = (start + end)/2;
invokeAll(new SqrtTransform(data, start, middlle),new SqrtTransform(data, middlle, end));
}
}
}
package ForkJoindemo;
import java.util.concurrent.ForkJoinPool;
/**
* @author firethinks
*
*/
public class ForkJoinDemo {
public static void main(String[] args) {
// 创建一个任务池
ForkJoinPool fjp = new ForkJoinPool();
double[] data = new double[100000];
// 给数组里添加值
for (int i = 0; i < 100000; i++) {
data[i] = (double) (i * 2);
}
// 显示出数组里的初始值
System.out.println("数组的初始值(一部分):");
for (int i = 0; i < 10; i++)
System.out.print(data[i] + " ");
System.out.println();
//创建ForkJoin任务
SqrtTransform task = new SqrtTransform(data, 0, data.length);
fjp.invoke(task);
//查看输出效果
System.out.println("处理后的结果:");
for (int i = 0; i < 10; i++) {
System.out.format("%4f ",data[i]);
}
}
}
演示结果如下:
数组的初始值(一部分):
0.0 2.0 4.0 6.0 8.0 10.0 12.0 14.0 16.0 18.0
处理后的结果:
0.000000 1.414214 2.000000 2.449490 2.828427 3.162278 3.464102 3.741657 4.000000 4.242641