1.分而治之 fork join
标准使用范畴:
/** * 统计集合数据的和 */ public class ForkJoinTest1 { private static class SumTest extends RecursiveTask<Integer> { //阀值 private final static Integer THRESHOLD = MakeArray.ARRAY_LENGTH/10; private int [] arry; // 处理的数据 private int start;//起点 private int end;//终点 public SumTest(int[] arry, int start, int end) { this.arry = arry; this.start = start; this.end = end; } @Override protected Integer compute() { if (end - start < THRESHOLD) { int sum = 0; for (int i= start;i<end;i++) { sum += arry[i]; } return sum; }else { int mid = (end + start)/2; SumTest left = new SumTest(arry,start,mid); SumTest right = new SumTest(arry,mid + 1,end); invokeAll(left,right); return left.join() + right.join(); } } } public static void main(String[] args) { ForkJoinPool pool = new ForkJoinPool(); int [] src = MakeArray.makeArray(); //获取随机数组 SumTest sumTest = new SumTest(src,0,src.length - 1); pool.invoke(sumTest); System.out.println(sumTest.join()); } }
无返回值
public class ForkJoinTest2 { private static class TestTask extends RecursiveAction{ public TestTask(File path) { this.path = path; } private File path; @Override protected void compute() { List<TestTask> list = new LinkedList(); File [] file = path.listFiles(); if (file != null) { for (File f: file ) { if (f.isDirectory()) { list.add(new TestTask(f)); }else{ if (f.getAbsolutePath().endsWith("txt")) { System.out.println(f.getAbsolutePath()); } } } if (list != null) { for (TestTask test:invokeAll(list)) { test.join();//等其他子线程 } } } } public static void main(String[] args) { //pool调度总任务 ForkJoinPool pool = new ForkJoinPool(); TestTask testTask = new TestTask(new File("/Volumes/H/Users/huangxu")); //异步调用 pool.execute(testTask); System.out.println("Task is Running......"); try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } int otherWork = 0; for(int i=0;i<100;i++){ otherWork = otherWork+i; } System.out.println("Main Thread done sth......,otherWork="+otherWork); testTask.join();//阻塞的方法 System.out.println("Task end"); } } }
来源:oschina
链接:https://my.oschina.net/u/3900969/blog/3196532