Hi, programmer mates. I was testing java threading capabilities with a very simple code (or at least it seemed simple). I have this class Account:
public class Account {
protected double balance;
public synchronized void withdraw(double value) {
this.balance = this.balance - value;
}
public synchronized void deposit(double value) {
this.balance = this.balance + value;
}
public synchronized double getBalance() {
return this.balance;
}
}
And I have two threads: Depositer
, that deposits $10 a thousand times:
public class Depositer extends Thread {
protected Account account;
public Depositer(Account a) {
account = a;
}
@Override
public void run() {
for(int i = 0; i < 1000; i++) {
this.account.deposit(10);
}
}
}
And Withdrawer
, that withdraws $10 a thousand times:
public class Withdrawer extends Thread {
protected Account account;
public Withdrawer(Account a) {
account = a;
}
@Override
public void run() {
for(int i = 0; i < 1000; i++) {
this.account.withdraw(10);
}
}
}
This arrangement is executed by:
public class Main {
public static void main(String[] args) {
Account account = new Account();
Thread c1 = new Depositer(account);
Thread c2 = new Withdrawer(account);
c2.start();
c1.start();
System.out.println(account.getBalance());
}
}
As the methods are sychronized, I just expected that the balance was always 0 at the end, but this not happens sometimes. And I sincerely cannot figure out why. Can someone see where is my fault?