import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.TimeUnit;
public class ForkJoin {
private List<String> list = new ArrayList<String>();
private int groupNum =5; //分成5个小任务,分别获取list中的值
public void init() {
for(int i=0;i<20;i++) {
list.add("a" + i);
}
}
public static void main(String[] args) {
System.out.println("*");
ForkJoinPool pool = new ForkJoinPool();
ForkJoin a = new ForkJoin();
a.init();
int size = a.list.size();
Task task = a.new Task(0, size);
System.out.println("**");
pool.submit(task);
System.out.println("***");
try {
pool.awaitTermination(2, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Block the current thread until all tasks in the pool are finished
//Close the thread pool
System.out.println("****");
pool.shutdown();
}
class Task extends RecursiveAction{
private static final int MIN_SIZE = 8;
private int start;
private int end;
public Task(int start, int end) {
this.start = start;
this.end = end;
}
protected void compute() {
boolean canCompute = end-start<=MIN_SIZE?true:false;
if(canCompute) {
System.out.println("...");
for(int i=start;i<=end;i++) {
print(i);
}
}else {
System.out.println("---");
int pos = start;
int step = (end - start)/groupNum;
for(int i=0;i<groupNum;i++) {
int last = pos + step;
if(last> end) {
last = end;
}
System.out.println("pos=" + pos + ", end=" + last);
Task t = new Task(pos, last);
pos += step + 1;
t.fork();
}
}
}
void print(int i) {
System.out.println(Thread.currentThread().getName() + " " +list.get(i));
}
}
}