Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.List;
- import java.util.concurrent.ForkJoinPool;
- import java.util.concurrent.RecursiveAction;
- import java.util.function.Consumer;
- public class ForkJoinMain {
- private static List<String> members
- = Arrays.asList("a", "b", "c"
- ,"d", "e", "f"
- ,"g", "h", "i"
- ,"j", "k", "l");
- public void test(){
- ForkJoinPool forkJoinPool = new ForkJoinPool(4);
- CustomAction<String> task = new CustomAction<>(members, (item)->{
- System.out.println("foreach : " + item + " : "+ Thread.currentThread());
- });
- forkJoinPool.invoke(task);
- }
- public static void main(String[] args) throws InterruptedException {
- new ForkJoinMain().test();
- }
- public class CustomAction<T> extends RecursiveAction {
- private List<T> members;
- private Consumer<T> consumer;
- public CustomAction(List<T> members, Consumer<T> consumer){
- this.members = members;
- this.consumer = consumer;
- }
- @Override
- protected void compute() {
- if(members.size() > 3) {
- List<CustomAction<T>> subTasks = createSubTasks();
- subTasks.forEach(subTask -> {
- subTask.fork();
- });
- } else {
- members.forEach(consumer);
- }
- }
- private List<CustomAction<T>> createSubTasks(){
- List<CustomAction<T>> subTasks = new ArrayList<>();
- int half = (members.size() -1 )/2;
- subTasks.add( new CustomAction<>(members.subList(0, half), consumer) );
- subTasks.add( new CustomAction<>(members.subList(half, members.size()), consumer) );
- return subTasks;
- }
- }
- }
Add Comment
Please, Sign In to add comment