DiffLockOrder account1 = new DiffLockOrder(1000);
DiffLockOrder account2 = new DiffLockOrder(500);
Runnable target1= ()->account1.transfer(account2,200);
Runnable target2= ()->account2.transfer(account1,100);
new Thread(target1).start();
new Thread(target2).start();
public class LockWithPrivateStatic {
private int amount;
private static final Object lock = new Object();
public LockWithPrivateStatic(int amount){
this.amount=amount;
}
public void transfer(LockWithPrivateStatic target, int transferAmount){
synchronized (lock) {
if (amount < transferAmount) {
System.out.println("余额不足!");
} else {
amount = amount - transferAmount;
target.amount = target.amount + transferAmount;
}
}
}
}
使用相同的Order
我们产生死锁的原因是无法控制上锁的顺序,如果我们能够控制上锁的顺序,是不是就不会产生死锁了呢?
带着这个思路,我们给对象再加上一个id字段:
private final long id; // 唯一ID,用来排序
private static final AtomicLong nextID = new AtomicLong(0); // 用来生成ID
public DiffLockWithOrder(int amount){
this.amount=amount;
this.id = nextID.getAndIncrement();
}