Using threads and recursion in Java to calculate Fibonacci numbers - java

I'm relatively new in the Java world and I have a problem which I don't understand.
I have a Class (to get the fibonacci row):
class Fib {
public static int f(int x){
if ( x < 2 )
return 1;
else
return f(x-1)+ f(x-2);
}
}
The task now is to start f(x-1) and f(x-2) each in a separate Thread.
One time with implementing the Thread class and the other with implementing Runnable.
As you probably know, it's an exercise from my prof.
I know how to start a Thread in Java and I know how this whole Thread thing theoretically works, but I can't find a solution for starting separate Threads in this recursive function.
What has to be done in the run function?
Probably
public void run(){
//int foo=start f(this.x-1)
//int bar=start f(this.x-2)
//return foo+bar?
}
And how can I paste x in my runnable function?
Is x passed into the object at creation?
Class Fib ...{
int x;
public ... run ...
public ... f(x)....
}
in the main method
(new Fib(x)).start();
Or am I on a totally wrong path?

For this to work, you need 1) a way to pass the number into the new thread, 2) to start the thread, 3) to wait for the thread to finish, and 4) a way to get the result back from the thread.
You can pass in the number through the constructor. You can have a public data member called "answer" to contain the result of the computation. Starting the thread can be done with the start() method, and the join() method waits for the thread to complete.
The following example demonstrates this. That should be a good starting point; from here you can abstract away some of the messiness to get a better API as desired.
public class Fib extends Thread
{
private int x;
public int answer;
public Fib(int x) {
this.x = x;
}
public void run() {
if( x <= 2 )
answer = 1;
else {
try {
Fib f1 = new Fib(x-1);
Fib f2 = new Fib(x-2);
f1.start();
f2.start();
f1.join();
f2.join();
answer = f1.answer + f2.answer;
}
catch(InterruptedException ex) { }
}
}
public static void main(String[] args)
throws Exception
{
try {
Fib f = new Fib( Integer.parseInt(args[0]) );
f.start();
f.join();
System.out.println(f.answer);
}
catch(Exception e) {
System.out.println("usage: java Fib NUMBER");
}
}
}

Using threads is usually intended to improve performance. However each thread adds an overhead and if the task performed is small, there can be much more over head than actual work done. Additionally most PCs can only handle about 1000 threads and will hang if you have much more than 10K threads.
In your case, fib(20) will generate 6765 threads, fib(30) creates 832K, fib(40) creates 102M threads, fib(50) creates over 12 trillion. I hope you can see this is not scalable.
However, using a different approach you can calculate fib(1000000) in under one minute.
import java.math.BigInteger;
/*
250000th fib # is: 36356117010939561826426 .... 10243516470957309231046875
Time to compute: 3.466557 seconds.
1000000th fib # is: 1953282128707757731632 .... 93411568996526838242546875
Time to compute: 58.1 seconds.
*/
public class Main {
public static void main(String... args) {
int place = args.length > 0 ? Integer.parseInt(args[0]) : 250 * 1000;
long start = System.nanoTime();
BigInteger fibNumber = fib(place);
long time = System.nanoTime() - start;
System.out.println(place + "th fib # is: " + fibNumber);
System.out.printf("Time to compute: %5.1f seconds.%n", time / 1.0e9);
}
private static BigInteger fib(int place) {
BigInteger a = new BigInteger("0");
BigInteger b = new BigInteger("1");
while (place-- > 1) {
BigInteger t = b;
b = a.add(b);
a = t;
}
return b;
}
}

You've got the right idea about starting threads in the fib function, and about passing x to the object through the constructor; you'll also need to have a way to get the result of the calculation out of the object at the end - I'm sure you can figure that out ;-) The thread-starting procedure you use in fib is just the same way you always start a thread, like (new Fib(x-1)).start() although you might want to save the thread in a variable because you'll need it to get the result of the computation later.

So with the help of you all I managed to do the same thing with implementing runnable instead of using the Thread Class.
Can you all have a look and tell me if thats the way how to do it if the task is to implement runnable.
The Code itself works.
public class Fib implements Runnable
{
private int x;
public int answer;
public Fib(int x) {
this.x = x;
}
public void run() {
if( x < 2 )
answer = 1;
else {
try {
Fib f1= new Fib(x-1);
Fib f2= new Fib(x-2);
Thread threadf1=new Thread(f1);
Thread threadf2=new Thread(f2);
threadf1.start();
threadf2.start();
threadf1.join();
threadf2.join();
answer = f1.answer + f2.answer;
}
catch(InterruptedException ex) { }
}
}
public static void main(String[] args)
{
try {
for (int i=0;i<19;i++){
Fib f= new Fib(i);
Thread threadf= new Thread(f);
threadf.start();
threadf.join();
System.out.println("Ergebnis:"+f.answer);
}
}
catch(Exception e) {
System.out.println("usage: java Fib NUMBER");
}
}
}

Related

This thread program shows me different answers every time

This is a Java Program to Find The Number with Largest Divisors from 1-500000.
public class Medium2 {
static int count1 = 1;
static int count2 = 1;
static int big_count = 0;
static int big = 0;
Main method
public static void main(String[] args) {
Runnable runnable1 = new Runnable() {
public void run() {
The implementation goes here
for (int num = 1; num <= 500000; num++) {
for (int i = 2; i <= num; i++) {
if (num % i == 0) { //Actual Logic
count1++;
}
}
if (count1 > big_count) {
big_count = count1; //Number of Divisors
big = num; //Largest Number
}
count1 = 1;
}
}
};
And the thread execution
Thread thread1 = new Thread(runnable1); //Threads
Thread thread2 = new Thread(runnable1);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException ie) {
;
}
System.out.println("Biggest: " + big + "\nNumber of Divisors for " + big + " = " + big_count);
}
}
But it gives different answers every time. The actual answer is : 498960 and 200 Divisors
Concerning your goal, your implementation should probably have problems. Since big_count and big is common for both threads and don't have any protection when threads are trying to modify those, your program should create errors.
Other than that, you are also not utilizing 2 threads, since both threads are doing calculation from 1 to 500000.
Since your calculation logic seems ok, you should get your desired output when you try with single thread.
If you want it to do by two threads, you can easily try this. (just to verify, not the nicest way)
You should have big_count1, big1 and big_count2, big2. So that variables whose names end with '1' is only using by thread1 and variables whose names end with '2' is only using by thread2.
Assign thread1 to check from 1 to 250000 and thread2 to from 250001 to 500000.
After join() s, just compare big_count1 and big_count2, then you can deduce the final answer. :))

which thread finished first in concurrent threads?

I am new in concurrent threads in java. I am trying to code a simple horse race simulation.
I want to know which thread finished first.
This code below throws an error: incompatible types: Thread cannot be converted to Gate
winner = (Gate)Thread.currentThread();
Gate.java
public class Gate implements Runnable{
public String horseName;
public final int GATE_DISTANCE = 20;
public final int FINISH_LINE_DISTANCE = 100;
public CyclicBarrier barrier;
public Gate(CyclicBarrier barrier,String horseName){
this.horseName = horseName;
this.barrier = barrier;
}
public void run(){
//Walk all horses to respective racing gates before starting race
for(int distanceCovered = 0; distanceCovered < GATE_DISTANCE;){
distanceCovered += gallop();
int distanceLeft = GATE_DISTANCE - distanceCovered;
if(distanceLeft < 0){
distanceLeft = 0;
}
System.out.println(horseName + "\t\tgate distance left " + distanceLeft);
if(distanceLeft == 0){
break;
}
}
//Wait for all horses to be at racing gates
try{
barrier.await();
}
catch(InterruptedException ie){
System.out.println("INTERRUPTED");
}
catch(BrokenBarrierException bbe){
System.out.println("BROKEN");
}
//ACTUAL HORSE RACE
for(int distanceCovered = 0; distanceCovered < FINISH_LINE_DISTANCE;){
distanceCovered += gallop();
int distanceLeft = FINISH_LINE_DISTANCE - distanceCovered;
if(distanceLeft < 0){
distanceLeft = 0;
}
System.out.println(horseName + "\t\tgate distance left " + distanceLeft);
if(distanceLeft == 0){
break;
}
}
Main.done();
}
public int gallop(){
final int MIN_GALLOP = 1,
MAX_GALLOP = 10;
Random random = new Random();
int gallopRange = MAX_GALLOP - MIN_GALLOP + 1;
int totalGallop = random.nextInt(gallopRange) + MIN_GALLOP;
return totalGallop;
}
}
GateMain.java
public class GateMain{
private static Gate winner = null;
public static void main(String[] args) {
int horseCount = 5;
List<String> horseNames = new ArrayList<String>();
List<Thread> RG = new ArrayList<Thread>();
horseNames.add("Red Bullet");
horseNames.add("Green Furious");
horseNames.add("Pink Mirage");
horseNames.add("Blue Dash");
horseNames.add("Yellow Burst");
Scanner scan = new Scanner(System.in);
final CyclicBarrier cb = new CyclicBarrier(horseCount,new Runnable(){
public void run(){
System.out.print("\nALL HORSES ARE IN THEIR RESPECTIVE RACING GATES");
System.out.println("\nRACE BEGIN!!!\n");
}
});
for(int horseCtr = 0; horseCtr < horseCount; horseCtr++){
Gate rg = new Gate(cb,horseNames.get(horseCtr));
Thread thread = new Thread(rg);
thread.start();
RG.add(thread);
}
for(Thread thread: RG){
try{
thread.join();
}
catch(InterruptedException ie){
System.out.println("Thread Interrupted");
}
}
System.out.println(winner.horseName + "\t\t\twins!");
}
synchronized static void done(){
if(winner == null){
winner = (Gate)Thread.currentThread();
}
}
}
I would use a global AtomicInteger.
public static AtomicInteger finishLine = new AtomicInteger(0);
Each horse (thread) should have its own place variable,
int place;
and when a horse finishes the race, it sets its own place:
place = finishLine.incrementAndGet();
The first horse to reach the finish line will get place=1, the second horse, place=2, and so on. Then the main() routine must then examine each horse to find out which one has place=1. That'll be the winner.
Here's a different idea, inspired by the finish-line of a cross-country foot race: Instead of an AtomicInteger, use a thread-safe queue.
public static ArrayBlockingQueue<Horse> chute =
new ArrayBlockingQueue<>(NUMBER_OF_HORSES);
When each horse reaches the finish line, it enters the chute.
chute.add(this);
This way, there is no need to explicitly wait for the race to end, and there is no need to explicitly sort the finishers:
Horse win = chute.take(); //waits for the first horse to finish
Horse place = chute.take(); //waits for the second horse
Horse show = chute.take(); //...
However, just synchronizing here will not work, according to the rules of Java. You have to synchronize the update that you want the thread to read, as well. Depending on what variable is, that may or may not be a problem.
You may need to think out your threading model a bit more, and describe here what you want to do. If you were unaware of mutual exclusion, you may not be ready to design threaded code.
if you're trying to access an instance field from a static member, I have to wonder how you got the code to compile.
Thread.currentThread() returns the actual Thread object you (or some other library code) created. That can be a Gate thread, but it all depends on the Thread object it is running in. Safest is to use instanceof to check first.
According to docs Thread.currentThread() returns a reference to the current thread, not the object. So, you should look for reference to the object i.e this keyword.
You wish to have winner as a private member. You can't change it from run() in another class. So, you can pass the current object from run() as an argument to a method in GateMain by this.
You can edit the done() method as:
synchronized static void done(Gate new_gate){
if(winner == null){
winner = new_gate;
}
}
Replace the line Main.done() with Main.done(this)

Why am I getting different results by 2 Threads even that my method is synchronized?

This is the code I am running:
public class MyRunnableClass implements Runnable {
static int x = 30;
int y = 0;
#Override
public void run() {
for(int i=0;i<30;i++){
getFromStash();
}
}
public synchronized void getFromStash(){
x--;
y++;
}
}
and my Test class:
public class MyRunnableClassTest {
public static void main(String[] args){
MyRunnableClass aa = new MyRunnableClass();
MyRunnableClass bb = new MyRunnableClass();
Thread a = new Thread(aa);
Thread b = new Thread(bb);
a.start();
b.start();
System.out.println(aa.y);
System.out.println(bb.y);
}
}
Sometimes I see output:
30
30
and sometimes I see:
30
0
Why? The method I have, is synchronized?
I actually expect to see something like 15 - 15 but it is definetly not what I am getting.
You need to wait for the threads to finish.
a.start();
b.start();
a.join();
b.join();
System.out.println(aa.y);
System.out.println(bb.y);
At that point you should see predictable results.
Added
Now you've had a chance to play - here's my attempt at what you seem to be trying to do.
public class MyRunnableClass implements Runnable {
static AtomicInteger stash = new AtomicInteger(1000);
int y = 0;
#Override
public void run() {
try {
while (getFromStash()) {
// Sleep a little 'cause I'm on a single-core machine.
Thread.sleep(0);
// Count how much of the stash I got.
y += 1;
}
} catch (InterruptedException ex) {
System.out.println("Interrupted!");
}
}
public boolean getFromStash() {
// It must be > 0
int was = stash.get();
while (was > 0) {
// Step down one.
if (stash.compareAndSet(was, was - 1)) {
// We stepped it down.
return true;
}
// Get again - we crossed with another thred.
was = stash.get();
}
// Must be 0.
return false;
}
}
Remove the bb and use only the aa object to create the two threads.
It's synchronized on this and you use two different objects (i.e. this values) - aa and bb. So practically you defeat the whole synchronization idea by using the two different objects.
Thread a = new Thread(aa);
Thread b = new Thread(aa);
a.start();
b.start();
Alternatively, you can do something like this.
public class MyRunnableClass implements Runnable {
private static final Object lock = new Object();
static int x = 30;
int y = 0;
#Override
public void run() {
for(int i=0;i<30;i++){
getFromStash();
}
}
public void getFromStash(){
synchronized(lock){
x--;
y++;
}
}
}
Here is what I think you want to achieve.
class Stash {
private int x = 30;
private int y = 0;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public synchronized void getFromStash(){
System.out.println("Method getFromStash called by " + Thread.currentThread().getName() + ".");
x--;
y++;
}
}
public class MyRunnableClass implements Runnable {
private Stash st = null;
private volatile boolean done = false;
public MyRunnableClass(Stash st){
this.st = st;
}
#Override
public void run() {
for(int i=0;i<30;i++){
this.st.getFromStash();
try {
double m = Math.random();
Thread.sleep((long)((m + 1) * 100.0));
}catch(InterruptedException ex){
ex.printStackTrace();
}
}
System.out.println("Thread ---> " + Thread.currentThread().getName() + " finished!");
this.done = true;
}
public static void main(String[] args) throws Exception {
Stash st = new Stash();
MyRunnableClass aa = new MyRunnableClass(st);
MyRunnableClass bb = new MyRunnableClass(st);
Thread a = new Thread(aa);
Thread b = new Thread(bb);
a.setName("Thread A");
b.setName("Thread B");
a.start();
b.start();
while (true){
System.out.println(st.getX() + " " + st.getY());
Thread.sleep(10);
if (aa.done && bb.done) break;
}
System.out.println("Main thread finished too!");
}
}
Since you print the values right after you start the threads, you're not going to "catch" the threads in the middle of the for loops. The thread scheduler is returning control to the main thread sometimes after the threads are done and sometimes before they start, but never during run(). You have to wait until the threads are done.
As you've already figured out, your first attempt didn't work the way you wanted because 1) you weren't waiting for the threads to finish, so sometimes you read the values before they'd done their work, and 2) you're not looking for each thread to pull from the stash 30 times, but rather for the sum total of the pulls to be 30 (divided among the threads however it happens).
Your move to stopping each thread when x > 0 instead of after N pulls is the right approach, but the test for whether x > 0 (and therefore whether to continue) needs to be synchronized as well. Otherwise you could test the value and find that x == 1, decide to do a pull, and then before you actually do it the other thread takes the last one. Then you do your pull, leaving x at -1 and the sum of the two y's at 31.
To solve this, you either need to put a check for x > 0 within the synchronized getFromStash() method (so you don't actually change x and y unless it's safe to do so), or you need to expose the lock outside the Stash object from peter.petrov's answer, so that both threads can explictly synchronize on that object when they test x > 0 and then call getFromStash() if applicable.
Also, it's generally much harder to figure out thread synchronization when you're using static variables; there tend to be interactions you don't anticipate. You're much better off creating a separate object (e.g. peter.petrov's Stash class) to help you represent the pool, and the pass a reference to it to each of your thread classes. That way all access is via non-static references, and you'll have an easier time making sure you get the code right.

How to make one thread object stop the other thread object in java

I have a class here that will be used as a thread/Runnable object, the second class below (UseSearch) has a main method that intantiates two instances of the Search class and uses them to create two threads. As you can see, the run method calls the add method that runs the loop depending on the direction passed in. I am looking for a mechanism that will cause one of the threads to stop the other thread's loop from iterating when the other thread has finished running it's iteration. Any help/advise will be highly appreciated. I have seen a similar example but it's far too complex for me to comprehend. - Jevison7x
public class Search implements Runnable
{
int sum;
boolean direction;
String name;
public Search(String n, boolean positive)
{
this.direction = positive;
this.name = n;
}
void add()
{
if(direction == true)
{
for(int i = 0; i < 100; i++)
{
sum += 1;
System.out.println(name+" has "+sum);
}
}
else
{
for(int i = 0; i < 100; i++)
{
sum -= 1;
System.out.println(name+" has "+sum);
}
}
}
public void run()
{
add();
}
}
public class UseSearch
{
public static void main(String[] args)
{
Search s1 = new Search("bob", true);
Search s2 = new Search("dan", false);
Thread t1 = new Thread(s1);
Thread t2 = new Thread(s2);
t1.start();
t2.start();
}
}
The thread that is doing the iterating needs to test something on each iteration to see if it has been told to stop. That could be a custom flag (implemented in a variety of ways) or a the thread's interrupted flag.
If you are going to use interrupt, then Matt Clark's answer is half of the picture. The other half is that the iterating thread needs to do something like this:
if (Thread.currentThread.isInterrupted()) {
// pause or stop or break out of the loop or whatever
}
... in the body of the relevant loop or loops.
Note: there is no safe way in Java to stop or pause another thread that is not regularly checking to see if it should stop / pause; i.e. a thread that is not cooperating.
Long answer short...
Make the Threads class-wide variables so that each thread has access to the other:
Thread t1, t2;
public static void main(String[] args){
t1 = new Thread(){
public void run(){
t2.interrupt();
}
};
t2=new Thread(){
public void run(){
t1.interrupt();
}
};
}

Semaphores: Critical Section with priorities

I'm writing a program in Java that deals with Semaphores for an assignment. I'm still new to the idea of Semaphores and concurrency.
The description of the problem is as follows:
A vector V[] of booleans. V[i] is "True"if Pi needs to use the critical section.
A vector of binary semaphores B[] to block processes from entering their critical section: B[i] will be the semaphore blocking process Pi.
A special scheduler process SCHED is used whenever a blocked process needs to be awakened to use the critical section.
SCHED is blocked by waiting on a special semaphore S
When a process Pi needs to enter the critical section, it sets V[i] to "True", signals the semaphore S and then waits on the semaphore B[i].
Whenever SCHED is unblocked, it selects the process Pi with the smallest index i for which V[i] is "True". Process Pi is then awakened by signaling B[i] and SCHED goes back to sleep by blocking on semaphore S.
When a process Pi leaves the critical section, it signals S.
This is my code:
import java.util.concurrent.Semaphore;
public class Process extends Thread {
static boolean V[];
int i;
static Semaphore B[]; //blocking semaphore
static Semaphore S;
private static int id;
static int N;
static int insist = 0;
public static void process (int i, int n) {
id = i;
N = n;
V = new boolean[N];
}
private void delay () {
try {
sleep (random(500));
}
catch (InterruptedException p) {
}
}
private static int random(int n) {
return (int) Math.round(n * Math.random() - 0.5);
}
private void entryprotocol(int i) {
V[Process.id] = true;
int turn = N;
while (V[Process.id] == true && turn == N) {
System.out.println("P" + Process.id + " is requesting critical section");
signal(S);
}
critical(Process.id);
wait(B[Process.id]);
V[Process.id] = false;
}
private void wait(Semaphore S) {
if (Process.id > 0) {
Process.id--;
} else {
//add Process.id to id.queue and block
wait(B[Process.id]);
}
}
private void signal(Semaphore S) {
if (B[Process.id] != null) {
Sched(Process.id);
} else {
Process.id++; //remove process from queue
critical(Process.id); //wakes up current process
}
}
private void critical(int i) {
System.out.println("P" + Process.id + " is in the critical section");
delay();
exitprotocol(i);
}
private void exitprotocol(int i) {
System.out.println("P" + Process.id + " is leaving the critical section");
V[id] = false;
signal(S);
}
public void Sched(int i) {
if (B[Process.id] == null) {
signal(B[Process.id]);
}
wait(S);
}
public void run() {
for (int i = 0; i < 5; i++) {
Sched(i);
entryprotocol(Process.id);
try {
wait(Process.id);
}
catch (InterruptedException p) {
}
signal(S);
}
}
public static void main (String[] args) {
int N = 5;
Process p[] = new Process[N];
for (int i = 0; i < N; i++) {
p[i] = new Process();
p[i].start();
}
}
}
I believe my logic here is correct but I'm getting a lot of errors (such as Exception in thread "Thread-1" java.lang.NullPointerException). Can any shed some light on what I'm doing wrong & provide me with some help. It's greatly appreciated!
Your NPE is probably due to the fact that you never initialize your Semaphore array - but its hard to say without a proper stack trace.
Two pieces of advice:
1) You might want to give your class variables more meaningful names than :
B
N
S
V.
Imagine walking away from this project and revisiting it in 4 months and had to read through that.
2) Figure out your class model on on a white board before writing any code. You have methods that take semaphores with the same name as some of your static fields. What are the relationships of the objects in your program? If you don't know, odds are your program doesn't know either.

Categories

Resources