在这种情况下,线程如何同时获取两个对象的锁? [英] How can a thread acquire lock on two objects simultaneously as in this case?

查看:56
本文介绍了在这种情况下,线程如何同时获取两个对象的锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public void method(Type1 inst1, Type2 inst2) {
  synchronized(inst1) {
    synchronized(inst2) {
      //do something now
    }
  }
}

从这段代码中我可以理解,一旦一个线程进入该方法,它会在inst1上获取锁,然后在inst2上获取锁,不会释放inst1锁.我假设这两个对象都没有被其他线程锁定.

I can understand from this piece of code that once a thread enters the method, it acquires the lock on inst1, and then it acquires lock on inst2, without releasing inst1 lock. I assume that both of these objects are not locked by other thread.

  1. 如果一个线程一次只能获取一个对象的锁,并且只能当当前对象的锁被释放时拥有另一个锁,如何这段代码是否有效,或者更确切地说,它是我认为在某处见过的有效代码吗?
  2. 如果 Type1 和 Type2 相同呢?
  3. 如果我们使方法同步会发生什么,考虑到它驻留在方法的参数类型以外的类?

推荐答案

1.如果一个线程一次只能获取一个对象的锁,并且当当前对象的锁被释放时只能拥有另一个锁,那么这段代码如何有效,或者更确切地说,它是我认为我见过的有效代码什么地方?

1 . If a thread can acquire lock on only one object at once and can only own another lock when lock on current object has been released, how can this piece of code be valid, or rather, is it a valid code that I think I have seen somewhere?

这是一个有效的代码,锁不在方法所在的对象上,而是在inst1inst2上.另外,锁不在类上,而是针对每个对象

It is a valid code, the locks are not on the object where the method resides, but on inst1 and inst2. Also, the lock is not on the class, but for every object

2.如果 Type1 和 Type2 相同呢?

2 . And what if Type1 and Type2 are same?

同样,锁是在对象上,而不是在类上.如果inst1和inst2相同,则线程只有一个锁,同一个线程重新进入"锁是有效的

again, the locks are on the objects, not on the classes. if inst1 and inst2 are the same, then the thread has only one lock, it is valid for the same thread to "re-enter" the lock

3 .如果我们使方法同步,考虑到它驻留在方法的参数类型之外的类中,会发生什么?

3 . What happens if we make the method synchronized, considering it resides in a class other than the parameter types of the method?

然后,您还有另一个锁,这次是在执行方法的对象(而不是类)上.

Then you have yet another lock, this time on the object (not the class) where the method is being executed.

这篇关于在这种情况下,线程如何同时获取两个对象的锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆