I have read somewhere that these following fragments of code are equivalent regarding syncronized code:
public synchronized void printMsg() {
System.out.println("synchronized");
}
public void printMsg() {
synchronized(this) {
System.out.println("synchronized");
}
}
As far as I know though, when a Thread accesses a synchronized method on an Object, its non-synchronized methods are not locked, namely other Threads can access them using the same instance.
Observing the second fragment, I have the impression that since the code is synchronized on this
, a Thread accessing that code acquires the lock on the Object.
My question is whether the other class methods can be accessed by other Threads when an Thraed maintains the lock excecuting the method printMsg()
using the second code-snippet?
If no, the above methods are not exactly same. What is true?