可能重複:
synchronized block vs synchronized method?同步(這)阻止整個對象?
從接受這個問題的答案:In Java critical sections, what should I synchronize on? 我得知
public synchronized void foo() {
// do something thread-safe
}
和:
public void foo() {
synchronized (this) {
// do something thread-safe
}
}
做的事情完全一樣。但在第一種情況下,我們只使同步對象的一種方法,而在第二種情況下,我們使不可訪問的整個對象。那麼爲什麼這兩個代碼片段做同樣的事情呢?
http://stackoverflow.com/questions/1149928/what-is-the-difference-between-a-synchronized-method-and-synchronized-block-in-j?rq=1,http:// stackoverflow.com/questions/10185867/java-synchronized-difference-threading?rq=1,http://stackoverflow.com/questions/8519700/what-is-the-difference-between-a-synchronized-function-and-同步塊 – 2012-08-16 05:50:49