import java.util.*;
import java.lang.*;
class fib1 extends Thread
{ void fibonacci()
{
int n = 10, t1 = 0, t2 = 1;
System.out.println("First " + n + " terms: ");
for (int i = 1; i <= n; ++i)
{
System.out.print(t1 + " + ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
}
}
}
class fib2 extends Thread
{
fib1 f1;
fib2(fib1 f1)
{
this.f1=f1;
}
public synchronized void run()
{
f1.fibonacci();
}
}
class fib3 extends Thread
{
fib1 f1;
fib3(fib1 f1)
{
this.f1=f1;
}
public synchronized void run()
{
f1.fibonacci();
}
}
public class A extends Thread
{
public static void main(String[] args)
{
fib1 obj = new fib1();
fib2 a = new fib2(obj);
fib3 b = new fib3(obj);
a.start();
b.start();
}
}
I have written a code for fibonacci series and also implemented the concept of synchronization, however I don't understand the use of
fib1 f1;
fib2(fib1 f1)
{
this.f1=f1;
}
public synchronized void run()
{
f1.fibonacci();
}
I could have just made an object of fib1 class and used it to call the fibonacci method directly. What is the purpose of this keyword? Why do i need that here(significance) same goes for fib3 class? Why make a constructor of fib2 class then pass object of fib1 as an argument that could have been directly done without creating constructor