Art
Art

Reputation: 434

Multithreading - Synchronizing the block for all instances of an Object

I have a class as Calculate. I created two threads both working on different instances of this class and tried to get the value of i. But both are giving me same values.

I want if one thread of a instance is working then the thread working on other instance should wait.

public class Calculate {
    private int i=2;
    public  void showNumber(){
        synchronized(Calculate.class){
            i=i+2;
        }
        System.out.println(Thread.currentThread()+"Value of i is "+i);
    }
}

class Test1 implements Runnable{
    Calculate c=null;
    public Test1(Calculate c){
        this.c=c;
    }
    @Override
    public void run() {
        System.out.println(Thread.currentThread()+" Running");
        c.showNumber();
    }

}
public class ThreadingPractise {
    public static void main(String[] args) {
        Calculate c=new Calculate();
        Calculate c1=new Calculate();
        Thread t1=new Thread(new Test1(c),"t1");
        Thread t2=new Thread(new Test1(c1),"t2");
        t1.start();
        t2.start();
    }
}

Upvotes: 0

Views: 38

Answers (1)

Sagar Gandhi
Sagar Gandhi

Reputation: 965

make i as static. If you want to share the variable between threads. and synchronize showNumber method instead of Calculate.class so that only 1 thread will run it at a time.

Upvotes: 1

Related Questions