I have a problem with the following java code, this program always gives "KKBB" as the output (so it looks like synchronization works). Therefore, I cannot understand, since I am a local variable, why does synchronization work 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 method, so the synchronization will not work, please help me understand, thanks
source share