简体   繁体   English

RecursiveAction 如何与斐波那契一起工作?

[英]How does RecursiveAction work with Fibonacci?

How does recursion work in case of Fibonacci.在斐波那契的情况下递归如何工作。 The below example uses RecursiveAction which does not return any value.下面的示例使用不返回任何值的 RecursiveAction。 But still it is possible to calculate Fibonacci numbers.但是仍然可以计算斐波那契数。 I mean for example in case of Fibonacci(15).我的意思是例如在斐波那契(15)的情况下。 The threshold in below example is 10. So Fibonacci(15) cannot be calculated directly.下例中的阈值为 10。因此无法直接计算 Fibonacci(15)。 So 2 other tasks will be created.因此将创建另外 2 个任务。 ForkJoinFibonacci(n - 1) and ForkJoinFibonacci(n - 2). ForkJoinFibonacci(n - 1) 和 ForkJoinFibonacci(n - 2)。 So in the below example only the member variable "number" stores the calculated Fibonacci number.所以在下面的例子中,只有成员变量“number”存储了计算出的斐波那契数。 But it is never returned.但它永远不会被退回。 Only stored locally in each ForkJoinFibonacci class.So how can all the calculated numbers be summed up?只存储在每个 ForkJoinFibonacci class 的本地。那么如何将所有计算的数字相加呢?

public class ForkJoinFibonacci extends RecursiveAction {
    
        private static final long threshold = 10;
        private volatile long number;
    
        public ForkJoinFibonacci(long number) {
            this.number = number;
        }
    
        public long getNumber() {
            return number;
        }
    
        @Override
        protected void compute() {
            long n = number;
            if (n <= threshold) {
                number = fib(n);
            } else {
                ForkJoinFibonacci f1 = new ForkJoinFibonacci(n - 1);
                ForkJoinFibonacci f2 = new ForkJoinFibonacci(n - 2);
                ForkJoinTask.invokeAll(f1, f2);
                number = f1.number + f2.number;
            }
        }
    
        private static long fib(long n) {
            if (n <= 1) return n;
            else return fib(n - 1) + fib(n - 2);
        }
    }

To make it clear.说清楚。 It works.有用。 But I just do not know why it works.但我只是不知道它为什么起作用。

The summing is in the compute method.求和是在计算方法中。

Each recursive action stores its own calculation in number.每个递归操作都以数字形式存储自己的计算。 the compute method either finishes the calculation if it's small enough, storing it in the number field, or farms the work out to two more recursive actions, in which case it gets their results from their number field, sums them, and stores them in its own number field.如果计算方法足够小,则计算方法要么完成计算,将其存储在数字字段中,要么将工作分配给另外两个递归操作,在这种情况下,它从它们的数字字段中获取结果,对它们求和,并将它们存储在它的自己的号码字段。 the topmost recursive action exposes number through a getter.最顶层的递归操作通过 getter 公开数字。

An alternative way to write this is to replace the invokeAll with另一种编写方法是将 invokeAll 替换为

f1.fork();
f2.compute();
f1.join();

That way the current thread is busy computing instead of bringing in another thread and waiting for it to do its work.这样,当前线程忙于计算,而不是引入另一个线程并等待它完成工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM