根据我的理解,下面这段代码应该会导致死锁。原因是,当线程 t1 锁定静态对象 firstData 时,他已经获得了对该类的锁定。所以,当他试图锁定另一个静态对象 secondData 时,请求应该被阻塞。
但是,程序运行良好并打印*** Successfully acquired both the locks
锁定我在这里丢失的静态对象是什么?
public class Deadlock {
public static void main(String[] args) {
Thread t1 = new Thread(new DeadlockRunnable());
t1.start();
}
}
class DeadlockRunnable implements Runnable {
static Object firstData = new Object();
static Object secondData = new Object();
public void run() {
synchronized(firstData) {
synchronized(secondData) {
System.out.println("*** Successfully acquired both the locks");
}
}
}
}
对于所有回答锁在对象而不是类上的人,请看看这个