在Java 7中使用Fork Join的斐波那契 [英] Fibonacci using Fork Join in Java 7

查看:76
本文介绍了在Java 7中使用Fork Join的斐波那契的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个使用Java 7 ForkJoin的Fibonacci程序. 但是似乎有一个死锁.

This is a program for Fibonacci using Java 7 ForkJoin . But seems like there is a dead lock.

package ForkJoin;

import java.time.LocalTime;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

import static java.time.temporal.ChronoUnit.MILLIS;

class Fibonacci extends RecursiveTask<Integer>{

    int num;
    Fibonacci(int n){
        num = n;
    }

    @Override
    protected Integer compute() {
        if(num <= 1)
            return num;

        Fibonacci fib1 = new Fibonacci(num-1);
        fib1.fork();
        Fibonacci fib2 = new Fibonacci(num-2);
        fib2.fork();

        return fib1.join()+ fib2.join();
    }
}

public class ForkJoinFibonaaciEx {

    public static void main(String[] arg){
        LocalTime before = LocalTime.now();
        int processors = Runtime.getRuntime().availableProcessors();
        System.out.println("Available core: "+processors);
        ForkJoinPool pool = new ForkJoinPool(processors);
        System.out.println("Inside ForkJoin for number 50:  "+pool.invoke(new Fibonacci(50)));
        LocalTime after = LocalTime.now();
        System.out.println("Total time taken: "+MILLIS.between(before, after));
    }
}

JVisualVM ----显示存在死锁. 不知道真正的问题是什么.

JVisualVM ---- shows there is dead lock. Not sure what the real issue is.

此外,我注意到代码中,开发人员完成了一部分的派生调用,并为问题的另一半进行了计算.

Also, I have noticed codes where developers have done fork call for one portion and compute for other half of the problem.

例如在此示例中,它们使用的是fib1.fork()和fib2,它们不会分叉.

e.g. here in this example they use fib1.fork() and fib2 they don't fork.

您可以看到完整的示例 https://github.com/headius/forkjoin. rb/blob/master/examples/recursive/Fibonacci.java

You can see the full example https://github.com/headius/forkjoin.rb/blob/master/examples/recursive/Fibonacci.java

非常感谢您的帮助. 谢谢你,祝你生活愉快 带着敬意 十日假人

Your help is very much appreciated. Thank you and have a great With regards Deenadayal Manikanta

推荐答案

尝试一下:

class ComputeFibonacciTask extends RecursiveTask<Long> {

    private int n;

    public ComputeFibonacciTask(int n) {
        this.n = n;
    }

    protected Long compute() {
        if (n <= 1) {
            return Long.valueOf(n);
        }

        else {
            RecursiveTask<Long> otherTask = new ComputeFibonacciTask(n - 1);
            otherTask.fork();
            return new ComputeFibonacciTask(n - 2).compute() + otherTask.join();
        }
    }
}

这篇关于在Java 7中使用Fork Join的斐波那契的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆