死锁

死锁

1.通过锁的顺序来避免死锁的发生,比如使用System.identityHashCode()排序,或者源数据中就有可比较的键值,比如账户

package concurrent._deadLock;

public class Demo {
    public static void main(String[] args) {

    }
    //模拟两个人转账的问题
    private boolean transferMoney(Account fromAccount,Account toAccount){
        //如果两个HashCode一样的时候使用的obj
        Object tieLock = new Object();

        //计算连个hashCode
        int fromHash = System.identityHashCode(fromAccount);
        int toHash = System.identityHashCode(toAccount);
        
        //永远是先获取小的那个账户的锁
        if(fromHash < toHash){
            synchronized (fromAccount){
                synchronized (toAccount){
                    transfer(fromAccount,toAccount);
                }
            }
        }else if(fromHash > toHash){
            synchronized (toAccount){
                synchronized (fromAccount){
                    transfer(fromAccount,toAccount);
                }
            }
        }else {
            //如果两个相同
            synchronized (tieLock){
                synchronized (toAccount){
                    synchronized (fromAccount){
                        transfer(fromAccount,toAccount);
                    }
                }
            }
        }
        
        return true;
    }
    private void transfer(Account fromAccount,Account toAccount){

    }
}
class Account{

}
原文地址:https://www.cnblogs.com/da-peng/p/10029095.html