在it技术中,是否将锁定对象放在私有字段变量上(而不是使用锁定对象)是安全/可接受的做法?这样,我可以为不同的目的使用不同的锁。以下是示例:
class Test {
private Integer x = 0;
private Integer y = 0;
public void incrementX() {
synchronized(x) {
x++;
}
}
public void decrementX() {
synchronized(x) {
x++;
}
}
public void incrementY() {
synchronized(y) {
y++;
}
}
public void decrementY() {
synchronized(y) {
y++;
}
}
我应该为每个需要锁定的私有成员拥有一个锁对象吗?例如:
class Test {
private final Object xLock = new Object();
private final Object yLock = new Object();
private Integer x = 0;
private Integer y = 0;
...
}
我应该只使用一个普通锁来锁定所有需要锁定的私有变量吗?例如:
class Test {
private final Object objLock = new Object();
private Integer x = 0;
private Integer y = 0;
...
}