package org.chapter.thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Bank {
private final double[] accounts;
private Lock bankLock;
private Condition sufficientFounds;
public Bank(int n,double intialbalance) {
accounts=new double[n];
for (int i = 0; i < accounts.length; i++) {
accounts[i]=intialbalance;
bankLock=new ReentrantLock();
sufficientFounds=bankLock.newCondition();
}
}
public void transfer(int from,int to,double amount) throws InterruptedException{
bankLock.lock();
try {
//如果账户余额小于了转走的资金,此刻线程被加锁,处于等待状态,直到账户资金大于转走资金会被叫醒线程。
while(accounts[from]<amount)
sufficientFounds.await();
//打印当前线程
System.out.println("now thread name is :"+Thread.currentThread());
accounts[from] -=amount;
accounts[to] +=amount;
//叫醒线程
sufficientFounds.signalAll();
}
finally{
//释放锁
bankLock.unlock();
}
}
public double getTotalBalance(){
bankLock.lock();
try {
double sum=0;
for (double a : accounts) {
sum+=a;
}
return sum;
} finally {
bankLock.unlock();
}
}
public int getSize(){
return accounts.length;
}
public static void main(String[] args) throws InterruptedException {
Bank b=new Bank(5, 100);
b.transfer(1, 2, 150);
}
}
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Bank {
private final double[] accounts;
private Lock bankLock;
private Condition sufficientFounds;
public Bank(int n,double intialbalance) {
accounts=new double[n];
for (int i = 0; i < accounts.length; i++) {
accounts[i]=intialbalance;
bankLock=new ReentrantLock();
sufficientFounds=bankLock.newCondition();
}
}
public void transfer(int from,int to,double amount) throws InterruptedException{
bankLock.lock();
try {
//如果账户余额小于了转走的资金,此刻线程被加锁,处于等待状态,直到账户资金大于转走资金会被叫醒线程。
while(accounts[from]<amount)
sufficientFounds.await();
//打印当前线程
System.out.println("now thread name is :"+Thread.currentThread());
accounts[from] -=amount;
accounts[to] +=amount;
//叫醒线程
sufficientFounds.signalAll();
}
finally{
//释放锁
bankLock.unlock();
}
}
public double getTotalBalance(){
bankLock.lock();
try {
double sum=0;
for (double a : accounts) {
sum+=a;
}
return sum;
} finally {
bankLock.unlock();
}
}
public int getSize(){
return accounts.length;
}
public static void main(String[] args) throws InterruptedException {
Bank b=new Bank(5, 100);
b.transfer(1, 2, 150);
}
}