Simple Bank Account Program
Hi,
I have a simple program for testing threads below for the standard bank account problem. Can someone explain why I'm getting the following output? I thought that having a synchronized keyword would ensure that the thread would complete the entire method. Thanks.
Jack, Previous balance: 33.0, New balance: 34.0
Jack, Previous balance: 34.0, Jill, Previous balance: 0.0, New balance: 36.0
Jill, Previous balance: 36.0, New balance: 37.0
Code Java:
public class BankAccountThread extends Thread {
/* Shared variable that is accessed by multiple threads */
private static double accountBalance;
public BankAccountThread(String name) {
super(name);
}
public synchronized void deposit(double amount) {
System.out.print(this.getName() + ", Previous balance: " + accountBalance + ", ");
accountBalance = accountBalance + amount;
System.out.print("New balance: " + accountBalance + "\n");
}
public void run() {
for (int i=0; i < 100; i++) {
deposit(1);
}
}
public static void main(String[] args) {
new BankAccountThread("Jack").start();
new BankAccountThread("Jill").start();
}
}
Re: Simple Bank Account Program
I recommend reading about Synchronized methods
Synchronized Methods (The Java™ Tutorials > Essential Classes > Concurrency)
In particular the two bullet points about half way down the page, paying special attention to the key phrase 'same object'.