It's not a matter of better, just different.
When you synchronize a method, you are effectively synchronizing to the object itself. In the case of a static method, you're synchronizing to the class of the object. So the following two pieces of code execute the same way:
public synchronized int getCount() {
// ...
}
This is just like you wrote this.
public int getCount() {
synchronized (this) {
// ...
}
}
If you want to control synchronization to a specific object, or you only want part of a method to be synchronized to the object, then specify a synchronized
block. If you use the synchronized
keyword on the method declaration, it will synchronize the whole method to the object or class.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…