|
Shared variable mutual exclusion problem. Plz help
Hi Everyone!
I am very new to Java programming, therefore i apologize for any stupid question and i will really appreciate comments from anyone.
My problem is I am trying to make a parking facility on java which will have two enterances and two exits. when i run the thread the total ammount of cars in the parking space is not accurate. I guess it is the mutual exclusion problem which i am facing. Now i am trying to solve it using synchronisation. Could anyone please let me know what further steps do i need to take to solve this problem.
My program structure is i have a class for one shared variable i.e. Total. which is being used by both entrance and exit classes. i think this shared variable i.e. Total needs to by synchronised. My code for entrance and shared variable class is as follows:-
Shared variable class:-
public class variable
{
public static int Total;
}
Entrance class:-
public class Entrance extends Thread
{
int value1;
int X1;
variable S;
public Entrance()
{
variable S= new variable();
}
public Entrance(int ThreadName,int max)
{
X1=ThreadName;
value1=max;
}
public void run()
{
for(int Y1=0;Y1<value1;Y1++)
{
if(S.Total<50)
{
S.Total++;
System.out.println("Car in at "+X1+", Total =" +S.Total+"{"+(Y1+1)+"}");
}
}
}
}
object class:-
public class objects
{
variable S;
public objects()
{
S.Total=0;
Entrance Entrance1=new Entrance(1,50);
Entrance1.start();
Exit Exit1=new Exit(1,50);
Exit1.start();
Entrance Entrance2=new Entrance(2,50);
Entrance2.start();
Exit Exit2=new Exit(2,50);
Exit2.start();
}
}
|