public void method(Type1 inst1, Type2 inst2) {
synchronized(inst1) {
synchronized(inst2) {
//do something now
}
}
}
从这段代码可以理解,线程一旦进入方法,就获取了inst1的锁,然后又获取了inst2的锁,并没有释放inst1的锁。我假设这两个对象都没有被其他线程锁定。
- 如果一个线程一次只能获取一个对象的锁并且只能 当当前对象的锁被释放时拥有另一个锁,如何 这段代码是否有效,或者更确切地说,它是否是我认为我在某处看到的有效代码?
- 如果 Type1 和 Type2 相同怎么办?
- 如果我们让方法同步会发生什么,考虑到它驻留在 除了方法的参数类型之外的类?
最佳答案
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?
是有效代码,锁不在方法所在的对象上,而是在inst1
和inst2
上。另外,锁不在类上,而是在每个对象上
2 . And what if Type1 and Type2 are same?
同样,锁在对象上,而不是在类上。如果inst1和inst2相同,则线程只有一个锁,同一个线程“重入”锁是有效的
3 . What happens if we make the method synchronized, considering it resides in a class other than the parameter types of the method?
然后您还有另一个锁,这次锁在执行方法的对象(而不是类)上。
关于java - 在这种情况下,线程如何同时获取两个对象的锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23217190/