有没有人可以告诉我同步方法优于同步块的例子?
唯一真正的区别是一个同步块可以选择它同步的对象。一个同步方法只能使用'this'(或相应的类实例用于同步类方法)。例如,这些在语义上是等同的:
synchronized void foo() {
...
}
void foo() {
synchronized (this) {
...
}
}
后者更灵活,因为它可以竞争任何对象的关联锁,通常是成员变量。它也更精细,因为您可以在块之前和之后执行并发代码,但仍然在方法中。当然,通过将并发代码重构为单独的非同步方法,您可以轻松地使用同步方法。使用任何一个让代码更易理解的地方。
使用同步方法的块没有明显的优势。
也许唯一一个(但我不称之为优势)是你不需要包含对象的引用this。
方法:
public synchronized void method() { // blocks "this" from here....
...
...
...
} // to here
块:
public void method() {
synchronized( this ) { // blocks "this" from here ....
....
....
....
} // to here...
}