so I have been working on some Java Multithreading projects to better understand the matter. I wrote some code to solve a car park problem. Basically multiple cars in the form of threads are supposed to randomly enter and exit a set number of parking slots. I guess I haven't quite gotten behind the concept of Java synchronization yet.
Here is my code:
public class CarPark
{
private int slots;
public CarPark(int slots)
{
if(slots < 0)
slots = 0;
this.slots = slots;
}
// Try to enter the car park
public void tryParking(String car)
{
if (slots >= 1) // At least one free slot to park in the car park
{
park(car);
}
else if (slots <= 0) // If there is no free slot then the car has to wait
{
System.out.println(car + ": is waiting for a slot. Free slots: " + slots);
}
}
// Parking in the car park
private void park(String car)
{
slots--;
System.out.println(car + ": is parking. Free slots: " + slots);
}
// Leaving the car park
public void leave(String car)
{
slots++;
System.out.println(car + ": is leaving the car park. Free slots: " + slots);
}
public static void main( String[] args)
{
// 5 slots
CarPark carpark = new CarPark(5);
// 20 Cars
for (int i=1; i<=20; i++) {
Car a = new Car("Car " + i, carpark);
}
}
}
class Car extends Thread
{
private CarPark carpark;
public Car(String name, CarPark carpark)
{
super(name);
this.carpark = carpark;
start();
}
public void run()
{
try {
sleep((int)(Math.random() * 1000));
} catch( InterruptedException e) { }
carpark.tryParking(getName());
try {
sleep((int)(Math.random() * 2000));
}
catch( InterruptedException e) { }
carpark.leave(getName());
}
}
So now I am faced with the problem that cars are exiting the slots (and "produce" free slots) that never parked there in the first place. How do I get the cars to only exit if they parked in the car park first?