1
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

1 Answers1

0

The point of synchronization is to protect shared data from being accessed and modified concurrently by multiple threads, as well as for making sure changes made by a thread are visible to other threads. The idea is you might have some data structure like a map or list or something and you want to control access to it so only one thread at a time can change it.

If you want to practice using the synchronized keyword you can identify some data structure that you need to control access to, and wrap it in an object where you use the synchronized keyword on the object's methods to protect those methods that access the data structure.

Don't use synchronized on methods of threads. Use it on objects that you want to protect from access by concurrent threads.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
  • Okay. I will keep that in mind. In our college they did not teach data structures in java yet (in C it is taught). Anyway Thanks. Alsobcan you make 'this' keyword sensible here. I think 'this' is used to access a method of a different class (in this case). – Tanay Joshi Oct 26 '18 at 02:34
  • @Tanay: in an instance method ‘this’ is the object whose instance method is being called. In a constructor ‘this’ is the object being constructed. – Nathan Hughes Oct 26 '18 at 02:41