【JUC】Fork / Join 拆分合并
生活随笔
收集整理的這篇文章主要介紹了
【JUC】Fork / Join 拆分合并
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
分支合并例子
/*** 計算1+2+3...+100 , 拆分成多任務計算,最后匯總,拆分標準是最大最小值差值不超過10* 如果任務比較耗時,明顯多線程拆分要快得多*/ class MyTask extends RecursiveTask<Integer> {//拆分最大最小差值不超過10private static final Integer VALUE = 10;private int begin; //拆分開始值private int end; //拆分結束值private int result;//返回結果//創建有參構造public MyTask(int begin, int end){this.begin = begin;this.end = end;}//拆分合并過程@Overrideprotected Integer compute() {//判斷相加的兩個數差值是否大于10if((end - begin) <= VALUE) {//相加操作for(int i = begin; i <= end; i++) {result += i;try {TimeUnit.MICROSECONDS.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}}}else {//進一步拆分//二分拆分int mid = (begin + end) / 2;//拆分左邊MyTask task01 = new MyTask(begin, mid);;//拆分右邊MyTask task02 = new MyTask(mid + 1, end);//調用方法拆分task01.fork();task02.fork();//合并結果result = task01.join() + task02.join();}return result;} }public class ForkJoinDemo {public static void main(String[] args) throws ExecutionException, InterruptedException {long start = System.currentTimeMillis();//創建MyTask對象MyTask myTask = new MyTask(0,100);//創建分鐘合并池對象ForkJoinPool forkJoinPool = new ForkJoinPool();ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(myTask);//獲取最終合并之后的結果Integer result = forkJoinTask.get();System.out.println("result = " + result);//關閉池對象forkJoinPool.shutdown();long end = System.currentTimeMillis();System.out.println("花費時間:" + (end - start));int sum = 0;for (int i = 0; i <= 100; i++) {sum += i;TimeUnit.MICROSECONDS.sleep(100);}System.out.println("sum = " + sum);long end2 = System.currentTimeMillis();System.out.println("花費時間:" + (end2 - end));} }總結
以上是生活随笔為你收集整理的【JUC】Fork / Join 拆分合并的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 多陪陪聊/大橘树洞/夏日小野猫/糖恋树洞
- 下一篇: NFT Insider #73:淡马锡将