import java.util.Random;
public class ClassA{
int a = 0, b = 10;
Random rand = new Random();
public synchronized void add(){
if (a < 10){
a++;
b--;
};
}
public synchronized void subtract(){
if (b < 10){
b++;
a--;
}
}
public synchronized boolean check(){
return a + b == 10;
}
public static void main(String args[]){
ClassA a = new ClassA();
B ba = new B(a);
B bb = new B(a);
//notice these two threads are not associated with the object a!
Thread t11 = new Thread(bb);
Thread t22 = new Thread(ba);
t11.start();
t22.start();
}
}
class B implements Runnable{
ClassA a;
B(ClassA a){
this.a = a;
}
@Override
public void run(){
while (a.check()){
if (a.rand.nextInt(2) == 1)
a.subtract();
else
a.add();
} System.out.print("Out of sync");
}
}
I'm trying to understand java multi-threading better. So, I know that the saying goes only one thread can access an object instance and thus call that instance's method (in this case for example, the subtract method in class classA.
But what happens when, you still have the same instance of classA, a but two threads associated with a different class classB altogether trying to call a's methods? I expected that the message out of sync would never have been printed, but it did. Afterall, there's still only one object instance a, does that imply synchronization doesn't apply in this example?