Java codepublic class DeadLock {
private static Integer accountA = 1000; // 账户A,有1000元
private static Integer accountB = 2000; // 账户B,有2000元
public static void main(String[] args) throws Exception {
// 模拟A转账500元给B的过程
Thread a2b = new Thread(new Runnable() {
public void run() {
synchronized (accountA) { // 先拿出A的存折
System.out.println("Check A's account.");
try {
Thread.sleep(200); // 假设这句话负责检查下A够不够钱
} catch (InterruptedException e) {
}
System.out.println("A got " + accountA + ", try to start transfer.");
synchronized (accountB) { // 去拿B的存折(其实这里就是死锁发生的位置了)
// 从A存折取出500
accountA = accountA - 500;
// 存入B存折
accountB = accountB + 500;
System.out.println("Transfer A2B done, now A: " + accountA + ", B: " + accountB);
}
}
}
});
// 模拟B转账500元给A的过程
Thread b2a = new Thread(new Runnable() {
public void run() {
synchronized (accountB) { // 先拿出B的存折
System.out.println("Check B's account.");
try {
Thread.sleep(200); // 假设这句话负责检查下B够不够钱
} catch (InterruptedException e) {
}
System.out.println("B got " + accountB + ", try to start transfer.");
synchronized (accountA) { // 去拿A的存折(其实这里就是死锁发生的位置了)
// 从B存折取出500
accountB = accountB - 500;
// 存入A存折
accountA = accountA + 500;
System.out.println("Transfer B2A done, now A: " + accountA + ", B: " + accountB);
}
}
}
});
// 这两笔转账要求同时发生了
a2b.start();
b2a.start();
// join 只是负责等待这两笔转账业务的线程结束而已
a2b.join();
b2a.join();
}
}