I'm still learning Java and at the moment I'm on threads, so basically I'm trying to do an application in which we have an account, now I want to use two differents threads. One that adds money to the account every 1s and displays the balance, and the other which withdraw a certain amount every 1s from the account and displays the resulting balance. So I created my Account class and thus object
public class Account {
private double money;
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
Account (double money){
this.money=money;
}}
And I created two classes one that adds ans the other that withdraw
public class Add extends Thread {
Account obj;
Add koi;
Add(Account obj){
this.obj=obj;
}
public synchronized void add(Account obj, Add koi){
this.obj=obj;
this.koi=koi;
while(obj.getMoney()<100){
double top= obj.getMoney()+10;
obj.setMoney(top);
System.out.println("The balance is : "+obj.getMoney());
try{
Thread.sleep(1000);
}
catch(Exception e){
System.out.println(e.toString());
}}
}public void run(){
add(obj,koi);}}
public class Withdraw extends Thread{
Account obj;
Withdraw koi;
Withdraw(Account obj){
this.obj=obj;
}
public synchronized void with(Account obj, Withdraw koi){
this.koi=koi;
this.obj=obj;
while (obj.getMoney()<100){
double top= obj.getMoney()-9;
obj.setMoney(top);
System.out.println("The balance is : "+obj.getMoney());
try{
Thread.sleep(1000);
}
catch(Exception e){
System.out.println(e.toString());
}}
}public void run(){
with(obj,koi);}}
Here's the main class:
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Account Steve= new Account(10);
Add test= new Add(Steve);
Withdraw test1= new Withdraw(Steve);
test.start();
test1.start();
}}
The thing is when I run the program the add method does its job but when it displays the output the result is not what I'm expecting (the balance is 10 when the add method is invoked it is supposed to display 20 but I'm getting 11 so the result that it displays take into account the result of the withdraw method and that's not what I want)