简体   繁体   English

通过运行对象的同步方法获得对象的锁

[英]Obtaining the lock ofan object by running its synchronized method

Running a synchronized method gives the lock of its object to the one invoking that method. 运行同步方法会将其对象的锁定授予调用该方法的对象。

In the code of this Q, do i need to synchronize the block at all-- on object c itself or on anything else? Q的代码中,我是否需要使块完全同步-在对象c本身或其他任何对象上?

setInt() is a synchronized method. setInt()是一个同步方法。

In the line 在行中

c.setInt(c.getInt()+k); 

when setInt() is invoked, the lock of c is obtained since setInt() is synch'd and the lock isn't released before setInt() returns. 调用setInt()时,由于setInt()已同步并且在setInt()返回之前未释放该锁,因此获得了c的锁。 That's the entire block and no need t synch it(?) 这就是整个块,不需要同步它(?)

So, 所以,

 c.setInt(c.getInt()+k); 

would still be synchronized if i comment out "Line-A" & "Line-B" in the following code. 如果我在以下代码中注释掉“ Line-A”和“ Line-B”,仍将保持同步。 setInt() is synchronized here, getInt() isn't: 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
        }  
}

This got me curious all along. 这一直让我感到好奇。

TIA TIA

Your question is hard to understand but I think you are asking if you are locked for the full call sequence there, the answer is that you are not. 您的问题很难理解,但我想您是在问是否已锁定整个通话顺序,答案是您没有。 Effectively what you have put is the same as: 实际上,您输入的内容与以下内容相同:

 int tmp = c.getInt(); // will lock and then unlock c
 tmp += k;
 c.setInt(tmp); // will lock and then unlock c.

This is why for proper thread safety you need an increment method which does both the get and set within one synchronized block. 这就是为什么要确保适当的线程安全,您需要一个增量方法,该方法在一个同步块中进行get和set设置。

ie

 c.increment(k);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM