码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-02-01 17:45:32      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:

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

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

标签:

原文地址:http://www.cnblogs.com/hellocyc/p/4265765.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!