Created
December 11, 2017 10:10
-
-
Save circlee/7dd6855aa89307a2a8362ddc702d723e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment