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?
You do the following:
You need to wait for these threads to complete their processing:
If you interrupt your main Thread then you’ll need to do something with an interrupted exception. Assuming that none of your code does this, you should always, at a minimum, log the Exception. NOTE: You’ll get the
InterruptedExceptionnot if someone interruptsc1orc2, but if someone interrupts your main thread, the thread that callsjoin(). If someone has calledinterrupt()on your main thread but you don’t check for it, then you’ll probably get theInterruptedExceptionthe moment you calljoin().