zoukankan      html  css  js  c++  java
  • 死锁

    死锁

    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{
    
    }
  • 相关阅读:
    (CS模式)大学计算机基础考试系统
    四叶草的祝福
    做人的小故事!
    前天晚上回到北京了
    人生活的三种状态
    松口气了!
    Mysql一些基础用法
    云计算随想
    对vector与deque插值与遍历的性能数据
    gdb命令的常用调试选项
  • 原文地址:https://www.cnblogs.com/da-peng/p/10029095.html
Copyright © 2011-2022 走看看