Guest User

Untitled

a guest
Dec 13th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. import java.util.List;
  4. import java.util.concurrent.ForkJoinPool;
  5. import java.util.concurrent.RecursiveAction;
  6. import java.util.function.Consumer;
  7.  
  8. public class ForkJoinMain {
  9.  
  10.  
  11. private static List<String> members
  12. = Arrays.asList("a", "b", "c"
  13. ,"d", "e", "f"
  14. ,"g", "h", "i"
  15. ,"j", "k", "l");
  16.  
  17.  
  18.  
  19. public void test(){
  20.  
  21.  
  22. ForkJoinPool forkJoinPool = new ForkJoinPool(4);
  23. CustomAction<String> task = new CustomAction<>(members, (item)->{
  24.  
  25. System.out.println("foreach : " + item + " : "+ Thread.currentThread());
  26. });
  27.  
  28. forkJoinPool.invoke(task);
  29. }
  30.  
  31.  
  32. public static void main(String[] args) throws InterruptedException {
  33.  
  34. new ForkJoinMain().test();
  35.  
  36. }
  37.  
  38.  
  39. public class CustomAction<T> extends RecursiveAction {
  40.  
  41. private List<T> members;
  42. private Consumer<T> consumer;
  43.  
  44. public CustomAction(List<T> members, Consumer<T> consumer){
  45. this.members = members;
  46. this.consumer = consumer;
  47. }
  48.  
  49. @Override
  50. protected void compute() {
  51.  
  52. if(members.size() > 3) {
  53. List<CustomAction<T>> subTasks = createSubTasks();
  54.  
  55. subTasks.forEach(subTask -> {
  56. subTask.fork();
  57. });
  58.  
  59.  
  60. } else {
  61. members.forEach(consumer);
  62. }
  63. }
  64.  
  65. private List<CustomAction<T>> createSubTasks(){
  66.  
  67. List<CustomAction<T>> subTasks = new ArrayList<>();
  68.  
  69.  
  70. int half = (members.size() -1 )/2;
  71. subTasks.add( new CustomAction<>(members.subList(0, half), consumer) );
  72. subTasks.add( new CustomAction<>(members.subList(half, members.size()), consumer) );
  73.  
  74. return subTasks;
  75. }
  76. }
  77.  
  78.  
  79.  
  80. }
Add Comment
Please, Sign In to add comment