i am currently working with locks in java and synchronizing methods. I have an example program with three classes: an account, with two methods for withdrawing and depositing money and a shared variable balance; and the Spender and Saver classes.
class Account{
private float balance = 0;
public void depositMoney(float amount){
float tmp;
synchronized(this){
tmp = balance;
System.out.println("(Adding money): the initial balance is: "
+ tmp);
tmp +=amount;
balance = tmp;
System.out.println("(Adding money): the final balance is: "
+ balance);
this.notify();
}
}
public void withdrawMoney(float amount){
float tmp;
synchronized(this){
while (balance <= 0){
try {
this.wait();
} catch (Exception e) {}
}
tmp = balance;
System.out.println("(Withdrawing money): the initial balance is: "
+ tmp);
tmp -=amount;
balance = tmp;
System.out.println("(Withdrawing money): the final balance is: "
+ balance);
}
}
}
class Saver extends Thread{
private Account account;
Scrooge(Account account){
this.account = account;
}
public void run(){
for (int i=0; i < 2; i++){
account.depositMoney(1200);
}
}
}
class Spender extends Thread{
private Account account;
Donald(Account account){
this.account = account;
}
public void run(){
for (int i=0; i< 2; i++){
account.withdrawMoney(400);
}
}
}
public class Bankv4{
public static void main(String[] args){
Account account = new Account();
Spender s1 = new Spender(account);
Spender s2 = new Spender(account);
Spender s3 = new Spender(account);
Saver saver = new Saver(account);
s1.start();
s2.start();
s3.start();
saver.start();
}
}
The problem is that this code does not always work. It works in the case that the Saver class runs the depositMoney method 30 times with a quantity of 100 and the Spender class runs the withdrawing money 10 times with a quantity of 100 (as there are 3 Spender Threads 10 * 3 * 100 = 3000, the amount that the Saver class deposit in the account).
In the code above, the problem is that although the Saver class is depositing the same quantity as the Spender is withdrawing, it does it in less iterations, which causes a deadlock as the Spender threads run wait() but the Saver class does not run notify() as its thread has ended, causing the program not to finish.
Can anyone solve this? Thanks in advance