[英]Obtaining the lock ofan object by running its synchronized method
运行同步方法会将其对象的锁定授予调用该方法的对象。
在此 Q的代码中,我是否需要使块完全同步-在对象c
本身或其他任何对象上?
setInt()
是一个同步方法。
在行中
c.setInt(c.getInt()+k);
调用setInt()
时,由于setInt()
已同步并且在setInt()
返回之前未释放该锁,因此获得了c
的锁。 这就是整个块,不需要同步它(?)
所以,
c.setInt(c.getInt()+k);
如果我在以下代码中注释掉“ Line-A”和“ Line-B”,仍将保持同步。 setInt()在这里同步,getInt()不是:
public void update(SomeClass c) {
while (<condition-1>) // the conditions here and the calculation of
// k below dont have anything to do
// with the members of c
if (<condition-2>) {
// calculate k here
synchronized (c) { // Line-A
c.setInt(c.getInt()+k);
// System.out.println("in "+this.toString());
} // Line-B
}
}
这一直让我感到好奇。
TIA
您的问题很难理解,但我想您是在问是否已锁定整个通话顺序,答案是您没有。 实际上,您输入的内容与以下内容相同:
int tmp = c.getInt(); // will lock and then unlock c
tmp += k;
c.setInt(tmp); // will lock and then unlock c.
这就是为什么要确保适当的线程安全,您需要一个增量方法,该方法在一个同步块中进行get和set设置。
即
c.increment(k);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.