-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBank.java
More file actions
60 lines (46 loc) · 1.13 KB
/
Bank.java
File metadata and controls
60 lines (46 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package synch;
import java.util.concurrent.locks.*;
public class Bank {
private final double[] accounts;
private Lock bankLock;
private Condition sufficientFunds;
public Bank(int n,double initialBalance){
accounts=new double[n];
for(int i=0;i<accounts.length;i++){
accounts[i]=initialBalance;
bankLock=new ReentrantLock();
sufficientFunds=bankLock.newCondition();
}
}
public void transfer(int from,int to,double amount)throws InterruptedException{
bankLock.lock();
try{
while(accounts[from]<amount)
sufficientFunds.await();
System.out.print(Thread.currentThread());
accounts[from]-=amount;
System.out.printf("%10.2f from %d to %d", amount,from,to);
accounts[to]+=amount;
System.out.printf("Total Balance:%10.2f%n",getTotalBalance());
//sufficientFunds.signalAll();
sufficientFunds.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 size(){
return accounts.length;
}
}