I have two thread that have access to an object. with synchronized(a), i supply lock on object a so now in each time on thread can access to object "a" and modify that.if execute this code we have 1 2. without synchronized block some times we get 2 2 .(thread t1 get i and increment i now thread t2 get i and increment that then thread t1 get i and print 2 ,also thread t2 get i and print 2) if i am true why we can not use synchronized(this) instead of synchronized(a)?
public class Foo {
public static void main(String[] args) {
B b =new B();
b.start();
}
}
class B{
A a = new A();
Thread t1 =new Thread(new Runnable(){
public void run(){
synchronized(a){
a.increment();
}
}
});
Thread t2 =new Thread(new Runnable(){
public void run(){
synchronized(a){
a.increment();
}
}
});
public void start(){
t1.start();
t2.start();
}
}
class A{
int i = 0;
public void increment() {
i++;
System.out.println(i);
}
}