package com.zzj.concurrency;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
/**
* 计算一千万个1到100之间的数值之和,此示例使用没有返回值的任务,没有合并结果
* @author lenovo
*
*/
public class ForkJoinTest {
static int[] nums = new int[10000000];
static int max_num = 50000;
static{
Random r = new Random();
for (int i = 0; i < nums.length; i++) {
nums[i] = r.nextInt(100);
}
}
/**
* 没有返回值
* @author lenovo
*
*/
static class AddTask extends RecursiveAction{
private static final long serialVersionUID = 1L;
private int start;
private int end;
public AddTask(int start, int end) {
this.start = start;
this.end = end;
}
@Override
protected void compute() {
if (end - start <= max_num) {
int s = 0;
for (int i = start; i < end; i++) {
s += nums[i];
}
System.out.println("from " + start + " to " + end + ":" + s);
} else {
int middle = start + (end - start) / 2;
AddTask addTask1 = new AddTask(start, middle);
AddTask addTask2 = new AddTask(middle, end);
addTask1.fork();
addTask2.fork();
}
}
}
public static void main(String[] args) throws IOException {
ForkJoinPool pool = new ForkJoinPool();
pool.execute(new AddTask(0, nums.length));
System.in.read(); // 必须阻塞,ForkJoinPool线程是后台线程
}
}
ForkJoin框架示例(一)
最新推荐文章于 2022-04-04 16:08:34 发布