I am learning Java multithreading. This is the the code I write.
package com.company;
public class Account {
private double balance = 100;
public synchronized double getBalance() {
synchronized (this){
return balance;
}
}
public void setBalance(double balance) {
this.balance = balance;
}
public boolean withdraw(double amount,String name){
if(this.getBalance()>amount){
if(Thread.currentThread().getName().equals("customer0")){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.setBalance(this.getBalance() - amount);
System.out.println(Thread.currentThread().getName() + " withdraw " + amount);
System.out.println("Hello, " + Thread.currentThread().getName() + " You current balance is " + this.getBalance());
return true;
}
else{
System.out.println("Sorry, " + Thread.currentThread().getName() + ". Your current balance is " + this.getBalance() + " and you cannot withdraw " + amount);
//System.out.println("Welcome, " + Thread.currentThread().getName() + " Your current balance is " + this.getBalance());
return false;
}
}
}
and the main class
package com.company;
import org.omg.PortableServer.THREAD_POLICY_ID;
public class Main implements Runnable {
Account account = new Account();
public static void main(String[] args){
Main main = new Main();
for(int i= 0; i< 2; i++) {
Thread c1 = new Thread(main, "customer" + i);
c1.start();
}
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "'s balance is " + account.getBalance());
account.withdraw(60, Thread.currentThread().getName());
//
}
}
I put synchronized keyword at getBalance() to make sure it can be accessible only by one thread a time. But still I get the negative balance.
customer0's balance is 100.0
customer1's balance is 100.0
customer1 withdraw 60.0
Hello, customer1 You current balance is 40.0
customer0 withdraw 60.0
Hello, customer0 You current balance is -20.0
What did I do wrong?