Last active
December 11, 2015 23:58
-
-
Save williamho/4680006 to your computer and use it in GitHub Desktop.
Multi-threaded non-recursive fibonacci. Not any more efficient than a single-threaded version.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Fib implements Runnable { | |
int curr=1, prev=1, counter=0, num; | |
Fib(int num) { | |
this.num = num; | |
} | |
private synchronized void calc() { | |
try { | |
System.out.println(Thread.currentThread().getName() + ": " + curr); | |
int tmp = curr; | |
curr += prev; | |
prev = tmp; | |
} | |
catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
public void run() { | |
while(counter++ < num) | |
calc(); | |
} | |
public static void main(String args[]) { | |
int num = 1; | |
try { | |
num = Integer.parseInt(args[0]); | |
} catch (Exception e) { | |
System.out.println("first argument must be a whole number"); | |
System.exit(-1); | |
} | |
Fib f = new Fib(num); | |
for (int i=0; i<5; i++) | |
(new Thread(f)).start(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment