【发布时间】:2014-06-18 08:46:30
【问题描述】:
运行同步方法会将其对象的锁提供给调用该方法的人。
在thisQ的代码中,
我需要在对象c 本身或其他任何东西上同步块吗?
setInt() 是一种同步方法。
在一行
c.setInt(c.getInt()+k);
当setInt()被调用时,由于setInt()是同步的,所以获得c的锁并且
在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
}
}
这让我一直很好奇。
TIA
【问题讨论】:
-
不要向 SO 提出关于同一问题的大量问题。顺便说一句,我给了你一个answer to your first question,这样就不需要其他所有的东西了。
标签: java multithreading synchronization locking