あなたは物事を混ぜているようです。
まずは
public synchronized void method() {
}
同期の観点からは、次のものと同等です。
public void method() {
synchronized (this) {
}
}
長所/短所は既に述べられており、さまざまな重複により詳細情報が得られます。
第二に、
synchronized(someObject) {
//some instructions
}
これは、同期ブロック内の命令を 2 つのスレッドで同時に実行できないことを意味します。これは、実行するためにモニターを取得する必要があるsomeObject
ためです。(これは、 someObject が変更されない最終参照であると想定しています)。
あなたの場合、someObject
たまたま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).