唯一的區別是減少了一些可以提高性能的鎖操作。
例子:讓我們想象一下,我們有一個servlet這給上輸入一個大數目一系列因素,我們要算的servlet是如何頻繁啓動。問題是同步進入狀態變量requestsCount
//Poor performance
class PoorFactorizer implements Servlet {
private int requestsCount = 0;
public synchronized void service(ServletRequest req, ServletResponse res) {
BigInteger numberToFactorize = extractFromRequest(req);
BigInteger[] factors = factorize(numberToFactorize); // long lasting
// operation makes everyone wait
requestCount++;
encodeResponse(res, factors);
}
}
//Better perfomance
class PoorFactorizer implements Servlet {
private int requestsCount = 0;
public void service(ServletRequest req, ServletResponse res) {
BigInteger numberToFactorize = extractFromRequest(req);
BigInteger[] factors = factorize(numberToFactorize);
// since we need to guard only the class' state
// let's guard only the operation with the state
synchronized(this) {
requestCount++;
}
encodeResponse(res, factors);
}
}
UPD:你可以閱讀的傑作的「Java併發編程實踐」一個很好的解釋(第2章)。我強烈建議您從封面閱讀本書。
或http://stackoverflow.com/questions/1149928/what-is-the-difference-between-a-synchronized-method-and-synchronized-block-in-j – bdonlan 2012-04-17 06:00:17