嵌套在同一个对象上的同步代码块

huangapple go评论79阅读模式
英文:

nested syncronized block on one object

问题

下面是您提供的代码的翻译部分:

这是代码部分不需要翻译

请注意,我只翻译了您提供的代码部分,不包括问题和其他内容。如果您有任何更多的翻译需求,请随时告诉我。

英文:

Is it possible that the current instance of a Thread be able to lock itself and causes a deadlock? For example, in this part of code, I believe the current instance of thread can't enter to second synchronization block because it already has a lock on s1 and it can't lock it again. but the code doesn't work that way. and prints the message in the second synchronized block. can someone please explain to me what I am missing? Thank You.

public class DeadLock {

    final String s1="s1";


    Thread t1=new Thread("t1"){

        @Override
        public void run() {
            synchronized (s1) {
                synchronized (s1) {
                    System.out.println(" t1 thread..");

                }
            }
        }
    };



    public static void main(String[] args) {

        DeadLock deadLock=new DeadLock();
        deadLock.t1.start();



    }

}

答案1

得分: 3

Java的监视器是可重入的。像您在代码中演示的嵌套锁定一样,完全可以正常工作。当您可以从其他同步方法调用同一对象的同步方法时,就会发生这种情况。

英文:

Java monitors are reentrant. Nested locking such as you demonstrated in your code works just fine. This is what happens when you can call synchronized methods of the same object from other synchronized methods.

huangapple
  • 本文由 发表于 2020年9月15日 02:20:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63889838.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定