运行同步方法会将其对象的锁提供给调用该方法的方法。
在this Q的代码中,我需要在object c本身或任何其他地方同步块吗?
setInt()是一种同步方法。
在队伍中
c.setInt(c.getInt()+k); 当调用setInt()时,会获得c的锁,因为setInt()是同步的,并且在setInt()返回之前不会释放锁。这就是整个块,不需要同步它(?)
所以,
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
}
}这让我一直很好奇。
提亚
发布于 2014-06-18 16:48:14
你的问题很难理解,但我认为你是在问你是否锁定了那里的整个调用序列,答案是没有。实际上,您放置的内容与以下内容相同:
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);https://stackoverflow.com/questions/24281041
复制相似问题