请参考下面的代码为什么它不会造成死锁?
package com.test;
public class DeadLock {
private void method1() {
synchronized (Integer.class) {
method2();
}
}
private void method2() {
synchronized (Integer.class) {
System.out.println("hi there");
}
}
public static void main(String[] args) {
new DeadLock().method1();
}
}
按我的理解,在method2
代码不应该在任何情况下执行,因为method1
持有Integer.class
和method2
尝试锁再次访问Integer.class
锁。但令我惊讶的是,代码运行良好,它向控制台输出“hi there”。有人可以澄清吗?
互动(递归)互斥?在这种情况下,互斥锁可以从同一个线程获取多倍的时间,但会从多个线程中(死锁)锁定 – 2014-10-29 11:11:59
为什么你认为它应该死锁?它直截了当的不是吗? – SMA 2014-10-29 11:13:33
如果您只有一个线程,则无法获取锁定。 – Leonidos 2014-10-29 11:17:23