JAVA Fork Join Demo 1
生活随笔
收集整理的這篇文章主要介紹了
JAVA Fork Join Demo 1
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
package com.famous.thread.util;import java.util.concurrent.ForkJoinPool;import java.util.concurrent.Future;import java.util.concurrent.RecursiveTask;/*** fork join framwork test*?* @author zhenglong fork/join任務(wù)應(yīng)該是純內(nèi)存算法,而沒有I/O操作* ? ? ? ? 此外,應(yīng)該盡可能避免通過共享狀態(tài)來進(jìn)行任務(wù)間的通信,因?yàn)檫@通常意味著加鎖會(huì)被執(zhí)行。理想情況下,* ? ? ? ? 僅當(dāng)一個(gè)任務(wù)fork另一個(gè)任務(wù)或一個(gè)任務(wù)join另一個(gè)任務(wù)時(shí)才進(jìn)行任務(wù)通信。*/public class ForkJoinDemo {public static void main(String[] args) {ForkJoinPool forkJoinPool = new ForkJoinPool();CountTask task = new CountTask(1, 4);Future<Integer> result = forkJoinPool.submit(task);try {System.out.println(result.get());} catch (Exception e) {}}}class CountTask extends RecursiveTask<Integer> {private int min;private int max;private int threadCount;public int getMin() {return min;}public void setMin(int min) {this.min = min;}public int getMax() {return max;}public void setMax(int max) {this.max = max;}public int getThreadCount() {return threadCount;}public void setThreadCount(int threadCount) {this.threadCount = threadCount;}public CountTask(int min, int max) {this.min = min;this.max = max;}/***?*/private static final long serialVersionUID = 4618283439406101422L;@Overrideprotected Integer compute() {int sum = 0;boolean canCompute = (max - min) <= threadCount;// 小于if (canCompute) {for (int i = min; i <= max; i++)sum += i;} else {int mid = (max + min) / 2;CountTask leftTask = new CountTask(min, mid);CountTask rightTask = new CountTask(mid + 1, max);// 執(zhí)行子任務(wù)leftTask.fork();rightTask.fork();int leftResult = (int) leftTask.join();int rightResult = (int) rightTask.join();sum = leftResult + rightResult;}return sum;}}?
轉(zhuǎn)載于:https://my.oschina.net/payzheng/blog/691555
總結(jié)
以上是生活随笔為你收集整理的JAVA Fork Join Demo 1的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 航电 2041 超级楼梯
- 下一篇: MongoDB文档对象字段属性合并的2种