Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
理解java中的嵌套锁_Java - Fatal编程技术网

理解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函数中

对。它们将阻塞,等待获取
字符串的监视器

当在线程上时,由于某些原因,仍然在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?