理解java中的嵌套锁
我想了解这一点:理解java中的嵌套锁,java,Java,我想了解这一点: String string; public Test(String string){ this.string = string; ..... } public void foo(newObjectPerCall o) { synchronized (o) { //each thread can enter here because the object passed is always different
String string;
public Test(String string){
this.string = string;
.....
}
public void foo(newObjectPerCall o) {
synchronized (o) {
//each thread can enter here because the object passed is always different
....
synchronized (string) {
// acquire this lock if the String is free.
}
}
}
public synchronized void function() {
}
public static void main(){
Test test = new Test("hello");
for(int i = 0; i < 10;i++){
WorkerThread workerThread = new WorkerThread(test);
workerThread.start();
}
}
我的疑问是:
- 如果一个线程获取了内部锁,那么获取外部锁的其他线程将保留在
函数中foo
- 当在线程上时,由于某些原因,仍然在
函数之外,此线程能否获得foo
内测试实例的锁函数
字符串的监视器
当在线程上时,由于某些原因,仍然在foo函数之外,这个线程能否获得函数内部测试实例的锁
是的,它完全独立于其他监视器。synchronized
实例方法与主体为
synchronized (this) {
...
}
如果没有其他线程已经拥有此
的监视器,“新”线程可以获取它,而不管其他监视器拥有什么。但是,由于所有工作线程都使用相同的Test
实例,因此一次只能有一个线程“在”function()
中。这可能与另一个线程正在执行foo()
的同时发生。对不起,我只知道第一个问题的答案
if one thread acquire the inner lock, other threads that acquired the outer lock, will remains inside the foo function?
是的还有一件事,如果thread1同时获得了内部和外部锁,那么线程t2,正如您所说,可以进入
函数()
,在对象类构造函数中定义字符串是否有问题?@OiRc:如果代码编译,那么它没有使用构造函数中声明的局部变量。如果你能更新你的帖子来展示一个简短但完整的编译示例,这会很有帮助——这会比使用伪代码更容易解释。不过我还是建议不要锁定字符串引用。由于字符串实习,很容易出现意外的别名。我在写问题时犯了一个错误。请参阅update.ok,谢谢,因此foo()
的同步外部锁不会阻止其他未进入foo()
的线程的循环,在此之前,我希望您告诉我一个澄清,就像您已经做的那样。
if one thread acquire the inner lock, other threads that acquired the outer lock, will remains inside the foo function?