I am still learning Java and I am currently on topics, so basically I'm trying to make an application in which we have an account, now I want to use two different threads. One that adds money to the account every 1 s and displays the balance, and the other, which removes a certain amount every 1 s from the account and displays the final balance. So I created my Account class and thus an 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 the other, which outputs
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 is the main class:
public class Test {
public static void main(String[] args) {
Account Steve= new Account(10);
Add test= new Add(Steve);
Withdraw test1= new Withdraw(Steve);
test.start();
test1.start();
}}
, , , , , ( 10 add, 20, 11, , , , , )