# Fibonacci Series Using a Multi-threaded Java Program

• October 19th, 2009, 11:23 PM
firesauce
Fibonacci Series Using a Multi-threaded Java Program
Well...as the title says, I need to generate a Fibonacci series using Java's thread library (including Runnable, I assume). I really don't know where to begin. Here's all I have so far...

Code :

```import java.util.Scanner;   public class FibonacciThread { public static void main (String[] args) { int userInput, fibonacciOutput; Scanner scan = new Scanner(System.in); System.out.print("Please enter a non-negative number:"); userInput = scan.nextInt(); fibonacciOutput= fib(userInput); System.out.println("The " + userInput+ "th Fibonacci number = " + fibonacciOutput+ "."); }   public static int fib(int k) { if (k <= 2) { return 1; } else { return fib(k-1) + fib(k-2); }}}```

It's not much...I know. But I don't know where to begin. Here are more instructions on what I'm to do...
"Write a multithreaded program that generated a Fib series...User should enter number to generate to...the program will then generate a separate thread that will generate the Fib numbers, placing the sequence in data that is shared by the threads (an array is probably most convenient)..."

Any help will be greatly appreciated! :)
• October 20th, 2009, 12:53 AM
helloworld922
Re: Fibonacci Series Using a Multi-threaded Java Program
Something like this? Here's the Fibonacci generating part. I haven't quite figured out a good way to keep main from accessing the array too soon, so I put in a little sleep statement in the constructor. I also implemented a dynamic programming solution to finding fibonacci numbers rather than the simple recursive solution (many times faster). I've left the stuff out that you had for what number to calculate the fibonacci number of, but I'm sure you can figure that stuff out (hint: you have it right in your code).

Code :

```public class Fibonacci implements Runnable { int[] fib;   public static void main(String[] args) { int[] answers = new Fibonacci(10).getFib(); System.out.println(answer[9]); }   public Fibonacci(int num) { this.fib = new int[num]; new Thread(this).start(); try { Thread.sleep(1); } catch (InterruptedException exception) {} }   public void run() { synchronized (this.fib) { this.fib[0] = 1; this.fib[1] = 1; for (int i = 2; i < this.fib.length; i++) { this.fib[i] = this.fib[i - 1] + this.fib[i - 2]; } } }   public int[] getFib() { return this.fib; } }```