can anyone explain me this code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 9

can anyone explain me this code

class Customer{   int amount=10000;      synchronized void withdraw(int amount){   System.out.println("going to withdraw...");      if(this.amount<amount){   System.out.println("Less balance; waiting for deposit...");   try{wait();}catch(Exception e){}   }   this.amount-=amount;   System.out.println("withdraw completed...");   }      synchronized void deposit(int amount){   System.out.println("going to deposit...");   this.amount+=amount;   System.out.println("deposit completed... ");   notify();   }   }      class Test{   public static void main(String args[]){   final Customer c=new Customer();   new Thread(){   public void run(){c.withdraw(15000);}   }.start();   new Thread(){   public void run(){c.deposit(10000);}   }.start();      }}  

6th May 2019, 7:02 AM
Ritu
Ritu - avatar
2 Answers
+ 8
Looks like they are trying to create a customer class and objects that can deposit and withdraw amounts (of money). It seems to be designed to work in a multi threaded setting where the withdrawal operation has to wait to be notified by a deposit operation. However, as it is written I don't believe this program will work without some modification. A Java expert might be able to better explain. Danijel Ivanović ??
6th May 2019, 9:00 AM
Sonic
Sonic - avatar
+ 4
it works, it outputs: going to withdraw... Less balance; waiting for deposit... going to deposit... deposit completed... withdraw completed... it shows how wait() / notify() methods works first c.withdraw() on thread try take out 15000$ but there is only 10000$ so withdraw() thread go to wait() state. then main() start() next thread of the same object c.deposit() deposit() add 10000$ (now there is 20000$) deposit() then do notify() and because it is same object c.withdraw() method wake and continue its work and take out 15000$.
6th May 2019, 3:30 PM
zemiak