归并算法在多线程中的应用-fork/join多线程应用实例

求最大值

    假定我们有一组数字,我们需要求里面的最大值。用我们传统的方法来求的话,其代码实现如下:

public int solveSequentially() {  
        int max = Integer.MIN_VALUE;  
        for (int i=start; i max)  
                max = n;  
        }  
        return max;  
    }  

   这里,我们假定numbers这个数组保存着所有需要比较的数字。

    如果我们应用ForkJoinPool的方式,则其实现如下:

public class MaxWithFJ extends RecursiveAction {  
    private final int threshold;  
    private final SelectMaxProblem problem;  
    public int result;  
  
    public MaxWithFJ(SelectMaxProblem problem, int threshold) {  
        this.problem = problem;  
        this.threshold = threshold;  
    }  
  
    protected void compute() {  
        if (problem.size < threshold)  
            result = problem.solveSequentially();  
        else {  
            int midpoint = problem.size / 2;  
            MaxWithFJ left = new MaxWithFJ(problem.subproblem(0, midpoint), threshold);  
            MaxWithFJ right = new MaxWithFJ(problem.subproblem(midpoint +   
              1, problem.size), threshold);  
            left.fork();  
            right.fork();  
            result = Math.max(left.join(), right.join());  
        }  
    }  
}  

 

 我们可以看到,如果当我们在将任务拆分成更小的任务时,我们可以通过ForkJoinTask的fork()方法让子问题异步的执行。然后我们再使用join方法得到异步方法执行的结果。 

 

你可能感兴趣的:(归并算法在多线程中的应用-fork/join多线程应用实例)