URDINESH: SYNCHRONIZATION
Showing posts with label SYNCHRONIZATION. Show all posts
Showing posts with label SYNCHRONIZATION. Show all posts

Tuesday, May 20, 2014

JAVA CODE FOR SYNCHRONIZATION-BANK



PROGRAM:

class Account
{
int acno;
float amt;
Account(int a,float a1)
{
acno=a;
amt=a1;
System.out.println("\nNow,the Balance is:Rs."+amt);
}
synchronized void putamt(float a)
{
System.out.println("\nProcess::Depositing Amount");
System.out.println("Depositing in Account is :Rs."+a);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println("Exception is:"+e.toString());
}
amt+=a;
System.out.println("After Deposit,the Amount is:Rs."+amt);
}
synchronized float getamt(float a)
{
System.out.println("\nProcess::Withdrawing Amount");
System.out.println("Amount to be Withdraw is:Rs."+a);
if(a>amt)
{
System.out.println("\nDear Customer,Not Enough Money!!,Please Check your Balance.");
return 0;
}
else
{
amt-=a;
System.out.println("After Withdrawal,the Amount is:Rs."+amt);
return(a);
}

}
}
class deposit extends Thread
{
Account o;
deposit(Account t)
{
o=t;
}
public void run()
{
o.putamt(8000.00f);
}
}
class  withdraw extends Thread
{
Account b;
withdraw(Account t)
{
b=t;
}
public void run()
{
float r=b.getamt(500f);
            }
}
class Bank
{
public static void main(String arg[])
{
Account a=new Account(100,500.00f);
deposit d=new deposit(a);
withdraw w=new withdraw(a);
d.start();
w.start();
}
 }








OUTPUT:


Now,the Balance is:Rs.1500.0

Process::Depositing Amount
Depositing in Account is :Rs.10000.0
After Deposit,the Amount is:Rs.11500.0

Process::Withdrawing Amount
Amount to be Withdraw is:Rs.1500.0
After Withdrawal,the Amount is:Rs.10000.0

CODE FOR SYNCHRONIZATION - JOIN



PROGRAM:

class Maxthread extends Thread
{
int d[ ],index;
public Maxthread(int t[ ],int i)
{
d=t;
index=i;
}
public void run()
{
int max=d[0];
for(int i=1;i<d.length;i++)
if(d[i]>max)
max=d[i];
try
{
Thread.sleep(1000);   
}
catch(Exception e)
{
}
Joineg.v[index]=max;
System.out.println("\nMaximum of "+index+" Array is::"+max);
}
}
class Maxmax extends Thread
{
Thread a,b,c;
Maxmax(Thread t1,Thread t2,Thread t3)
{
a=t1;
b=t2;
c=t3;
}
public void run()
{
try
{
a.join();
b.join();
c.join();
}
catch(Exception e)
{
}
int m=Joineg.v[0];
for(int i=1;i<Joineg.v.length;i++)
{
if(Joineg.v[i]>m)
m=Joineg.v[i];
}
System.out.println("\n\nMaximum of all Three Array is::"+m);
}
}
class Joineg
{
static int v[ ]=new int[3];
public static void main(String arg[ ])
{
int x[ ]={125,256,302,14,436};
int y[ ]={347,137,618,198,1010};
int z[ ]={27,101,113,213,513};
Maxthread t,t2,t3;
t=new Maxthread(x,0);
t2=new Maxthread(y,1);
t3=new Maxthread(z,2);
Maxmax t1=new Maxmax(t,t2,t3);
t.start();
t1.start();
t2.start();
t3.start();
}
}



OUTPUT:


Maximum of 0 Array is::436

Maximum of 1 Array is::1010

Maximum of 2 Array is::513



Maximum of all Three Array is::1010

Followers