public boolean transferMoney(Account fromAcct,Account toAcct,DollarAmount amount,long timeout,TimeUnit unit) throws InsufficientFundsException,InterruptedException{
long fixedDelay = getFixedDelayComponentNanos(timeout,unit);
long randMod = getRandomDelayModulusNanos(timeout,unit);
long stopTime = System.nanoTime()+unit.toNanos(timeout);
while(true){
if(fromAcct.lock.tryLock()){
try{
if(toAcct.lock.tryLock()){
try{
if(fromAcct.getBalance().compareTo(amount) < 0)
throw new InsufficientFundsException();
else{
fromAcct.debit(amount);
toAcct.credit(amount);
return true;
}
}finally{
toAcct.lock.unlock();
}
}
}finally{
toAcct.lock.unlock();
}
if(System.nanoTime() < stopTime){
return false;
}
NANOSECONDS.sleep(fixedDelay+rnd.nextLong()%randMod);
}
通过t r yLock避免死锁
猜你喜欢
转载自blog.csdn.net/weixin_37632716/article/details/119334249
今日推荐
周排行