public class Test3 {private static List < FileInfo> fileList = new ArrayList < FileInfo > ();
// private static ForkJoinPool forkJoinPool=new ForkJoinPool(100);
// private static Job<FileInfo> job=new Job<>(fileList.size()/100, fileList);
public static void main(String[] args) {
createFileInfo();
long startTime = System.currentTimeMillis();
ForkJoinPool forkJoinPool = new ForkJoinPool(100);
// 分割任务
Job < FileInfo > job = new Job < >(fileList.size() / 100, fileList);
// 提交任务返回结果
ForkJoinTask < Integer > fjtResult = forkJoinPool.submit(job);
// 阻塞
while (!job.isDone()) {
System.out.println("任务完成!");
}
long endTime = System.currentTimeMillis();
System.out.println("fork/join 框架耗时:" + (endTime - startTime) + "ms");
}
private static void createFileInfo() {
for (int i = 0; i < 30000; i++) {
fileList.add(new FileInfo("身份证正面照", "jpg", "101522", "md5" + i, "1"));
}
}
}
/**
* 执行任务类
* @author wangsj
*
*/
public class Job < T > extends RecursiveTask < Integer > {
private static final long serialVersionUID = 1L;
private int count;
private List < T > jobList;
public Job(int count, List < T > jobList) {
super();
this.count = count;
this.jobList = jobList;
}
/**
* 执行任务, 类似于实现 Runnable 接口的 run 方法
*/
@Override protected Integer compute() {
// 拆分任务
if (jobList.size() <= count) {
executeJob();
return jobList.size();
} else {
// 继续创建任务, 直到能够分解执行
List < RecursiveTask < Long >> fork = new LinkedList < RecursiveTask < Long >> ();
// 拆分子任务, 这里采用二分法
int countJob = jobList.size() / 2;
List < T > leftList = jobList.subList(0, countJob);
List < T > rightList = jobList.subList(countJob, jobList.size());
// 分配任务
Job leftJob = new Job < >(count, leftList);
Job rightJob = new Job < >(count, rightList);
// 执行任务
leftJob.fork();
rightJob.fork();
return Integer.parseInt(leftJob.join().toString()) + Integer.parseInt(rightJob.join().toString());
}
}
/**
* 执行任务方法
*/
private void executeJob() {
for (T job: jobList) {
try {
Thread.sleep(1);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
来源: https://www.cnblogs.com/10158wsj/p/8338367.html