I'm creating a car park in Java, I have one entrance and one exit. The car park has 20 spaces and and I think I've coded the entrance/exit correctly, I have been asked to use threading.
import java.io.*;
public class CarPark {
private int spaces;
public CarPark(int spaces)
{
if (spaces < 0) {
spaces = 0;
}
this.spaces = spaces;
}
public synchronized void entrance() //enter car park
{
while (spaces == 0) {
try {
wait();
} catch (InterruptedException e)
{
}
}
spaces --;
}
public synchronized void exit() // exit car park
{
spaces++;
notify();
}
}
I'm just a bit stuck on how to represent the actual parking garage itself and create the spaces which can be decremented or incremented as a car approaches or leaves. I have coded the below so far for the main method:
public static void main(String[] args){
CarPark parkingGarage = new CarPark(20); //20 spaces
}
Also when the spaces are full, cars need to queue for a space, it would be best to represent this as an integer I think. You may assume that cars cannot enter and leave simultaneously (i.e. the system will prevent this anyway from happening as a consequence of locking)
Eventually I need to make this into a client - server system.
Any advice is much appreciated!