可能重复:
避免在 Java 中同步(this)?
两段代码有什么区别?各自的优点和缺点是什么?
1)
public class Example {
private int value = 0;
public int getNextValue() {
synchronized (this) {
return value++;
}
}
}
2)
public class Example {
private final Object lock = new Object();
private int value = 0;
public int getNextValue() {
synchronized (lock) {
return value++;
}
}
}