英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论