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

使用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()方法出现异常时则直接抛出。


Java并发编程核心方法与框架-Fork-Join分治编程(一)的更多相关文章

  1. Java并发编程核心方法与框架-TheadPoolExecutor的使用

    类ThreadPoolExecutor最常使用的构造方法是 ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAli ...

  2. Java并发编程核心方法与框架-CountDownLatch的使用

    Java多线程编程中经常会碰到这样一种场景:某个线程需要等待一个或多个线程操作结束(或达到某种状态)才开始执行.比如裁判员需要等待运动员准备好后才发送开始指令,运动员要等裁判员发送开始指令后才开始比赛 ...

  3. Java并发编程核心方法与框架-Semaphore的使用

    Semaphore中文含义是信号.信号系统,这个类的主要作用就是限制线程并发数量.如果不限制线程并发数量,CPU资源很快就会被耗尽,每个线程执行的任务会相当缓慢,因为CPU要把时间片分配给不同的线程对 ...

  4. Java并发编程核心方法与框架-CompletionService的使用

    接口CompletionService的功能是以异步的方式一边生产新的任务,一边处理已完成任务的结果,这样可以将执行任务与处理任务分离.使用submit()执行任务,使用take取得已完成的任务,并按 ...

  5. Java并发编程核心方法与框架-ScheduledExecutorService的使用

    类SchedukedExecutorService的主要作用是可以将定时任务与线程池功能结合. 使用Callable延迟运行(有返回值) public class MyCallableA implem ...

  6. Java并发编程核心方法与框架-ExecutorService的使用

    在ThreadPoolExecutor中使用ExecutorService中的方法 方法invokeAny()和invokeAll()具有阻塞特性 方法invokeAny()取得第一个完成任务的结果值 ...

  7. Java并发编程核心方法与框架-Future和Callable的使用

    Callable接口与Runnable接口对比的主要优点是Callable接口可以通过Future获取返回值.但是Future接口调用get()方法取得结果时是阻塞的,如果调用Future对象的get ...

  8. Java并发编程核心方法与框架-Executors的使用

    合理利用线程池能够带来三个好处 降低资源消耗.通过重复利用已创建的线程降低线程创建和销毁造成的消耗. 提高响应速度.当任务到达时,任务可以不需要等到线程创建就能立即执行. 提高线程的可管理性.线程是稀 ...

  9. Java并发编程核心方法与框架-phaser的使用

    arriveAndAwaitAdvance()方法 arriveAndAwaitAdvance()作用是当前线程已经到达屏障,在此等待一段时间,等条件满足后继续向下一个屏障执行. public cla ...

随机推荐

  1. js学习笔记2---HTML属性操作

    1.HTML属性操作:读.写 属性名 属性值   2.属性读操作:获取.找到 a) 语法:元素.属性名 如:document.getElementById(“btn”).value; b) 字符串的连 ...

  2. 【USACO 2.2】Runaround Numbers

    找出第一个大于n的数满足:每一位上的数都不同,且没有0,第一位开始每次前进当前这位上的数那么多位,超过总位数就回到开头继续往前进,最后能不能每个位都到过一次且回到第一位,$n<10^9$. 暴力 ...

  3. iOS 蓝牙开发(四)BabyBluetooth蓝牙库介绍(转)

    转载自:http://www.cocoachina.com/ios/20151106/14072.html 原文作者:刘彦玮 BabyBluetooth 是一个最简单易用的蓝牙库,基于CoreBlue ...

  4. ORA-29538、ORA-29532、ORA-29913问题解决

    问题一:ERROR at line 1: ORA-29538: Java not installed解决方法1.检查有没有安装JAVA组件select * from v$option t where ...

  5. Redis_持久化之RDB

    rdb - Redis DataBase 官网介绍: 在指定的时间间隔内存中的数据集快照写入磁盘,也就是行话将的Snapshot快照,它恢复时是将快照文件直接读到内存中. 是什么: Redis会单独创 ...

  6. 【BZOJ-2839】集合计数 容斥原理 + 线性推逆元 + 排列组合

    2839: 集合计数 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 229  Solved: 120[Submit][Status][Discuss] ...

  7. 【BZOJ-1500】维修数列 Splay

    1500: [NOI2005]维修数列 Time Limit: 10 Sec  Memory Limit: 64 MBSubmit: 11047  Solved: 3460[Submit][Statu ...

  8. bzoj1396: 识别子串

    #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #i ...

  9. Bzoj2763 [JLOI2011]飞行路线

    Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 2651  Solved: 1004 Description Alice和Bob现在要乘飞机旅行,他们选 ...

  10. QTVA-2015-198545、WooYun-2015-104148 .NET Framework Arbitrary File Permissions Modify Vul

    catalog . Description . Effected Scope . Exploit Analysis . Principle Of Vulnerability . Patch Fix 1 ...