Java并发编程核心方法与框架-Fork-Join分治编程(一)

时间:2024-01-19 21:45:20

在JDK1.7版本中提供了Fork-Join并行执行任务框架,它的主要作用是把大任务分割成若干个小任务,再对每个小任务得到的结果进行汇总,这种开发方法也叫做分治编程,可以极大地利用CPU资源,提高任务执行的效率。

Java并发编程核心方法与框架-Fork-Join分治编程(一)

使用RecursiveAction分解任务

public class MyRecursiveAction extends RecursiveAction {

	private int beginValue;
private int endValue; public MyRecursiveAction(int beginValue, int endValue) {
super();
this.beginValue = beginValue;
this.endValue = endValue;
}
@Override
protected void compute() {
System.out.println("MyRecursiveAction.compute()----" + Thread.currentThread().getName());
if (endValue - beginValue > 2) {
int middleValue = (beginValue + endValue)/2;
MyRecursiveAction leftAction = new MyRecursiveAction(beginValue, middleValue);
MyRecursiveAction rightAction = new MyRecursiveAction(middleValue + 1, endValue);
invokeAll(leftAction, rightAction);
} else {
System.out.println("组合result:" + beginValue + "--" + endValue);
}
}
} public class Main {
public static void main(String[] args) throws InterruptedException {
ForkJoinPool pool = new ForkJoinPool();
pool.submit(new MyRecursiveAction(1, 10));
Thread.sleep(5000);
}
}

控制台输出结果如下:

MyRecursiveAction.compute()----ForkJoinPool-1-worker-1
MyRecursiveAction.compute()----ForkJoinPool-1-worker-1
MyRecursiveAction.compute()----ForkJoinPool-1-worker-1
组合result:1--3
MyRecursiveAction.compute()----ForkJoinPool-1-worker-1
组合result:4--5
MyRecursiveAction.compute()----ForkJoinPool-1-worker-1
MyRecursiveAction.compute()----ForkJoinPool-1-worker-1
组合result:6--8
MyRecursiveAction.compute()----ForkJoinPool-1-worker-1
组合result:9--10

使用RecursiveTask取得返回值

public class MyRecursiveTask extends RecursiveTask<Integer> {

	@Override
protected Integer compute() {
System.out.println("Time:" + System.currentTimeMillis());
return 100;
}
} public class Test1 {
public static void main(String[] args) {
try {
MyRecursiveTask task1 = new MyRecursiveTask();
System.out.println(task1.hashCode());
ForkJoinPool pool = new ForkJoinPool();
ForkJoinTask<Integer> task2 = pool.submit(task1);
System.out.println(task2.hashCode() + " " + task2.get());
} catch (Exception e) {
e.printStackTrace();
}
}
}

程序输出结果如下:

1311053135
Time:1473599556598
1311053135 100

也可以使用join()方法取得返回值

public class Test2 {
public static void main(String[] args) {
try {
MyRecursiveTask task1 = new MyRecursiveTask();
System.out.println(task1.hashCode());
ForkJoinPool pool = new ForkJoinPool();
ForkJoinTask<Integer> task2 = pool.submit(task1);
System.out.println(task2.hashCode() + " " + task2.join());
} catch (Exception e) {
e.printStackTrace();
}
}
}

程序输出结果如下

1311053135
Time:1473599778476
1311053135 100

方法join()和方法get()虽然都能取得计算后的结果值,但对异常的处理存在区别。使用get()方法执行任务时,当子任务出现异常时,可以在main线程中进行捕获。使用join()方法出现异常时则直接抛出。