JAVA Fork Join Demo 1

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任务应该是纯内存算法,而没有I/O操作

 *         此外,应该尽可能避免通过共享状态来进行任务间的通信,因为这通常意味着加锁会被执行。理想情况下,

 *         仅当一个任务fork另一个任务或一个任务join另一个任务时才进行任务通信。

 */

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;



@Override

protected 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);



// 执行子任务

leftTask.fork();

rightTask.fork();



int leftResult = (int) leftTask.join();

int rightResult = (int) rightTask.join();



sum = leftResult + rightResult;

}



return sum;

}



}

 

转载于:https://my.oschina.net/payzheng/blog/691555

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值