I have problem with following java code, this program always give "KKBB" as the output (so it seems like synchronization works ), So i am unable to understand since i is a local variable why synchronization is working here?
class Test implements Runnable {
public void run() {
Integer i=10;
synchronized(i)
{
try {
System.out.print(Thread.currentThread().getName());
Thread.sleep(1200);
System.out.print(Thread.currentThread().getName());
} catch (InterruptedException e) {
}
}
}
public static void main(String[] args) {
new Thread(new Test(), "K").start();
new Thread(new Test(), "B").start();
}
}
I heard that since local variables have different copies for each methods, so synchronization won't work, please help me to understand, thanks
synchronized(i)statement does not operate on the variable, it operates on the object to which the variable refers. As @chrylis pointed out,Integer.valueOf(10)always refers to the same cached Integer object.