前言:批量执行任务可以提炼为几个基本点:
1、任务的执行代码和结果收集。
2、提交任务。
3、执行任务的线程池。
一、执行单元
public class YourRecursiveAction extends RecursiveAction {
private YourService yourService; //用到的服务,可以多个
private YourParamDO yourParamDO; //你的参数,可以多个
private YourResultDO yourResultDO; //你要收集的结果
private Logger logger = LoggerFactory.getLogger(YourRecursiveAction.class);
public CheckResourceRecursiveAction(YourService yourService, YourParamDO yourParamDO, YourResultDO yourResultDO ) {
this.yourService = yourService;
this.yourParamDO = yourParamDO;
this.yourResultDO = yourResultDO;
}
@Override
protected void compute() {
/**
* 写入你要执行的代码并且可以收集结果通过上面的参数返回,同一个对象要注意线程安全。
**/
}
}
二、提交任务
public class ComposeTask extends RecursiveAction {
private List<RecursiveAction> concurrencyServiceList;
public ComposeTask(List<RecursiveAction> recursiveActionList) {
this.concurrencyServiceList = recursiveActionList;
}
@Override
protected void compute() {
/**
* 分别提交
*/
for( RecursiveAction recursiveAction: concurrencyServiceList ){
recursiveAction.fork();
}
/**
* 卡住,执行完成之后,再结束。
*/
for( RecursiveAction recursiveAction: concurrencyServiceList ){
recursiveAction.join();
}
}
}
三、任务线程池:
public class ComposeTaskPools {
private static ForkJoinPool forkJoinPool = new ForkJoinPool(500);
private static Logger Log = LoggerFactory.getLogger(ComposeTaskPools.class);
public static ForkJoinTask submitComposeTask( ComposeTask composeTask ){
try {
ForkJoinTask forkJoinTask = forkJoinPool.submit(composeTask);
forkJoinTask.join();
return forkJoinTask;
}catch ( Exception e ){
Log.error("submit task fail!",e);
return null;
}
}
}
四、任务调用
List<RecursiveAction> yourRecursiveActions = new ArrayList<>();
// YourRecursiveAction 上面定义的执行单元
yourRecursiveActions.add(new YourRecursiveAction(// 参数列表));
ComposeTaskPools.submitComposeTask( new ComposeTask( yourRecursiveActions ));