你似乎在混合东西。
首先
public synchronized void method() {
}
从同步的角度来看,等效于:
public void method() {
synchronized (this) {
}
}
已经提到了优点/缺点,并且各种重复提供了更多信息。
第二,
synchronized(someObject) {
//some instructions
}
means that the instructions in the synchronized block can't be executed simultaneously by 2 threads because they need to acquire the monitor on someObject
to do so. (That assumes that someObject is a final reference that does not change).
In your case, someObject
happens to be this
.
Any code in your object that is not synchronized, can still be executed concurrently, even if the monitor on this
is held by a thread because it is running the synchronized block. In other words, synchronized(this)
does NOT "lock the whole object". It only prevents 2 threads from executing the synchronized block at the same time.
Finally, if you have two synchronized
methods (both using this
as a lock), if one thread (T1) acquires a lock on this
to execute one of those 2 methods, no other thread is allowed to execute any of the two methods, because they would need to acquire the lock on this
, which is already held by T1.
That situation can create contention in critical sections, in which case a more fine grained locking strategy must be used (for example, using multiple locks).