模拟银行账户汇款操作(并发控制)

import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
* 模拟银行转账入账
*
*/
class Account implements Comparable<Account>{

private int balance;
public final Lock monitor = new ReentrantLock();

public Account(final int balance) {
this.balance = balance;
}

public int compareTo(Account other) {
return new Integer(hashCode()).compareTo(other.hashCode());//枷锁的顺序
}

/**
* 转出操作
*/
public boolean withdraw(final int amount) {
monitor.lock();
try {
if(balance >=amount && amount > 0) {
balance -= amount;
return true;
}

return false;
} finally {
monitor.unlock();
}
}

/**
* 存进操作
*/
public void deposit(int amount) {
monitor.lock();
try {
if(amount > 0)
balance += amount;
} finally {
monitor.unlock();
}
}

public int getBalance() {
return balance;
}

}

public class AccountService {
public boolean transfer(final Account from, final Account to, final int amount) {
final Account[] accounts = new Account[] {from, to};
Arrays.sort(accounts);
try {
if(accounts[0].monitor.tryLock(1,TimeUnit.SECONDS)) {
try {
if(accounts[1].monitor.tryLock(1,TimeUnit.SECONDS)) {
try {
if(from.withdraw(amount)) {
to.deposit(amount);
return true;
} else
return false;
} finally {
accounts[1].monitor.unlock();
}
}
} finally {
accounts[0].monitor.unlock();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}

return false;
}

public static void main(String[] args) throws InterruptedException {
final Account account1 = new Account(100);
final Account account2 = new Account(100);
final AccountService service = new AccountService();

final CountDownLatch latch = new CountDownLatch(2);
//account1和account2同时互转
new Thread(new Runnable() {

public void run() {
service.transfer(account1, account2, 55);
latch.countDown();
}
}).start();

new Thread(new Runnable() {

public void run() {
service.transfer(account2, account1, 35);
latch.countDown();
}
}).start();

latch.await();
System.out.println(account1.getBalance());
System.out.println(account2.getBalance());
}
}

转载于:https://www.cnblogs.com/hellocyc/p/4265765.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值