赞
踩
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());
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。