Code :
class Account
{
double balance = 10000.00;
synchronized public double withdraw( double wamt )
{
System.out.println(" Withdraw process starts ");
System.out.println(" Before Withdraw: "+balance);
if(balance < wamt)
{
System.out.println(" Sorry insufficient balance waiting for deposit ");
try
{
wait(); // if any thread calling wait() then it will release the lock in fraction of seconds and goes to wait() state life long until notify() method calls
// wait(1000); if you want to wait for some particular amount of time
}
catch( InterruptedException e )
{
e.printStackTrace();
}
}
balance = balance - wamt;
System.out.println(" After Withdraw: " + balance);
return wamt;
}
synchronized public void deposit( double damt )
{
System.out.println("\n\n Deposit process starts: ");
System.out.println(" Before Deposit : "+balance);
balance = balance + damt;
System.out.println(" After Deposit : "+balance);
notify();
// notifyAll(); // if you have multiple threads
}
}
public class Test extends Thread
{
public static void main(String args[]) throws InterruptedException
{
final Account acc = new Account();
new Thread()
{
public void run()
{
acc.withdraw(15000);
}
}.start();
new Thread()
{
public void run()
{
acc.deposit(5000);
}
}.start();
}
}
{
double balance = 10000.00;
synchronized public double withdraw( double wamt )
{
System.out.println(" Withdraw process starts ");
System.out.println(" Before Withdraw: "+balance);
if(balance < wamt)
{
System.out.println(" Sorry insufficient balance waiting for deposit ");
try
{
wait(); // if any thread calling wait() then it will release the lock in fraction of seconds and goes to wait() state life long until notify() method calls
// wait(1000); if you want to wait for some particular amount of time
}
catch( InterruptedException e )
{
e.printStackTrace();
}
}
balance = balance - wamt;
System.out.println(" After Withdraw: " + balance);
return wamt;
}
synchronized public void deposit( double damt )
{
System.out.println("\n\n Deposit process starts: ");
System.out.println(" Before Deposit : "+balance);
balance = balance + damt;
System.out.println(" After Deposit : "+balance);
notify();
// notifyAll(); // if you have multiple threads
}
}
public class Test extends Thread
{
public static void main(String args[]) throws InterruptedException
{
final Account acc = new Account();
new Thread()
{
public void run()
{
acc.withdraw(15000);
}
}.start();
new Thread()
{
public void run()
{
acc.deposit(5000);
}
}.start();
}
}