当前位置:   article > 正文

java模拟银行账户业务转账_模拟银行账户汇款操作(并发控制)

java如何实现a账户转账b账户,并发

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{

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());

}

}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/404467
推荐阅读
相关标签
  

闽ICP备14008679号