我正在尝试 Java 多线程中的死锁概念。我遇到了一个可能导致死锁的代码片段:
public class Deadlock {
double amount = 10.0;
public double deposit(double d) {
amount += d;
return amount;
}
public double withdraw(double d) {
amount -= d;
return amount;
}
public static void transfer(Deadlock from, Deadlock to,double d) {
synchronized(from) {
synchronized(to) {
from.withdraw(d);
try {
System.out.println(Thread.currentThread().getName());
Thread.sleep(5000);
}catch(Exception e){}
to.deposit(d);
System.out.println("Done");
}
}
}
public static void main(String[] args) {
final Deadlock a = new Deadlock();
final Deadlock b = new Deadlock();
Thread t1 = new Thread(new Runnable() {
public void run() {
transfer(a, b, 10.0);
}
});
t1.start();
Thread t2 = new Thread(new Runnable() {
public void run() {
transfer(b, a, 10.0);
}
});
t2.start();
}
}
基本上,代码尝试同时获取对象 a 和 b 上的锁。但是,当我运行它时,代码总是成功完成。为什么不会出现这种僵局?