//Synchronization in java example
class BankAccount
{
private int balance=100;
public int getBalance()
{
return balance;
}
public void withDraw(int amount)
{
balance=balance-amount;
}
}
public class OneAndTwo implements Runnable
{
private BankAccount account=new BankAccount();
public void run()
{
for(int x=0;x<10;x++)
{
makeWithDrawl(10);
if(account.getBalance()<0)
System.out.println("Overdrawn");
}
}
private void makeWithDrawl(int amount)
{
if(account.getBalance()>=amount)
{
System.out.println(Thread.currentThread().getName()+"is about to withdraw");
try
{
System.out.println(Thread.currentThread().getName()+"is going to sleep");
Thread.sleep(500);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println(Thread.currentThread().getName()+"is woke up");
account.withDraw(amount);
System.out.println(Thread.currentThread().getName()+"completes withdraw");
}
else
System.out.println("Sorry not enough for..."+Thread.currentThread().getName());
}
public static void main(String args[])
{
OneAndTwo ob1=new OneAndTwo();
Thread one=new Thread(ob1,"One");
Thread two=new Thread(ob1,"Two");
one.start();
two.start();
}
}