Java 7: Fork/Join Framework

前端 未结 6 685
深忆病人
深忆病人 2021-02-02 01:25

Can someone explain what Fork/Join is?

6条回答
  •  余生分开走
    2021-02-02 02:11

    In addition to what was already said, fork/join utilizes work stealing - threads that run out of things to do can steal tasks from other threads that are still busy. And here is an example that can help you to understand how FJ can be used:

    public class SumCounter extends RecursiveTask { 
    
      private final Node node; 
    
      public SumCounter(Node node) { 
        this.node = node; 
      } 
    
      @Override
      protected Long compute() { 
        long sum = node.getValue();
        List subTasks = new LinkedList<>(); 
    
        for(Node child : node.getChildren()) { 
          SumCounter task = new SumCounter(child); 
          task.fork(); // run asynchronously
          subTasks.add(task); 
        }
    
        for(SumCounter task : subTasks) { 
          sum += task.join(); // wait for the result 
        } 
    
        return sum;
      }
    
      public static void main(String[] args) { 
        Node root = getRootNode(); 
        new ForkJoinPool().invoke(new SumCounter(root)); 
      }
    
    }
    

提交回复
热议问题