4

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!

Aldwoni
  • 1,168
  • 10
  • 24
collision934
  • 31
  • 1
  • 9
  • 1
    What you've done seems fine. Try creating two threads - one which repeatedly calls the entrance method at regular intervals of time, and the other which repeatedly calls the exit method at regular intervals of time. Print the contents of the CarPark in the exit and entrance methods and run your code to see how it's working. – Akshay Damle Jan 06 '16 at 16:15
  • While you might not be able to use it (because you have to write lower level threading code), the Semaphore is designed to help you in this case (concept of permits, acquire, release) – Ian Mc Jan 06 '16 at 16:25
  • @AndyTurner I see the deadlock, however the specification I am working towards specifies locking as a requirement. – collision934 Jan 06 '16 at 16:47
  • Locking does not necessarily using `synchronized` methods, though - there are other ways of performing locking. If you have a particular specification, you should include pertinent details in your question. – Andy Turner Jan 06 '16 at 16:49
  • @AndyTurner was a bit shy to post exactly the spec as I didn't want to be seen to be asking for help on all off it, have now updated it. Thank you :) – collision934 Jan 06 '16 at 17:02
  • @AkshayDamle thanks for that, I guess I could repeatedly call it using sleep? I could then print the current state of spaces I presume? – collision934 Jan 06 '16 at 17:08
  • @collision934 Yes you can have a loop with one sleep statement and one entrance/exit method call statement in your thread's run method. You could have the print statement in the exit and entrance methods so that the state of spaces is printed to stdout every time a car enters/exits. – Akshay Damle Jan 06 '16 at 17:13
  • @AndyTurner How is a thread in the `wait()` call "holding the monitor for `this`"? A call to `o.wait()` is not allowed unless the calling thread holds a lock on `o`, and it _releases_ the lock while it is waiting. – Solomon Slow Jan 06 '16 at 20:13

3 Answers3

1

What you've done so far looks okay to me. All you need to do is use your CarPark object 'parkingGarage' to simulate a car entering or exiting.

For example:

parkingGarage.entrance();

This would simulate a car entering the garage and thus spaces would decrement.

Similarly, .exit() would do the same thing but increment the number of spaces. Although you would need to add checks to ensure that an exit can only occur if an entrance has occurred. For example, you could not have 10 entrances and 20 exits and the number of spaces would become negative.

Also, you could implement some sort of 'queue' so that when there are no spaces, the car waiting the longest will get a space first.

Threading allows you to run bits of code 'concurrently', could you please explain further what it is exactly you want/are trying to do.

EDIT:

After reading Akshay's comment, it cleared things up for me. Like they said, you could create two threads, one which handles entrances and one which handles exits and have each of these generate a random amount of time before the next car enters or exits. You would do this using:

Thread.sleep(randomAmountOfTime)

Note: The parameter for this is handled in milliseconds. Again, make note of my previous argument of not having more exits than entrances.

After this you could print out some sort of log which outputs a message when a car exits or enters or even have a dynamic 'sign' which displays the number of free spaces which would change when cars enter or exit.

Hope this helps.

James
  • 1,471
  • 3
  • 23
  • 52
  • thank you for that, I guess I should perhaps use arrays to ensure there are more than 20 cars? But I'm not sure, logically and in code, how the cars would then queue, I know I can represent it as an integer, but I am unsure how to make the entrance understand there is a queue. – collision934 Jan 06 '16 at 17:12
1

My opinion is each thread should represent a car. So I would have the main thread go into a loop:

for (;;) {
    Thread.sleep(randomAmountOfTime);
    // a new car has shown up
    spawn a new carThread
}

And each car thread would be something like:

System.out.println("Car " + carId + " has arrived");
parkingGarage.entrance();
System.out.println("Car " + carId + " has parked");
Thread.sleep(randomAmountOfTime);
parkingGarage.exit();
System.out.println("Car " + carId + " has left");
John Hascall
  • 9,176
  • 6
  • 48
  • 72
0

i think your code and logic is fine.. i have some suggessions,

  1. use multiple entry and exit door for car, so that your system will become advanced one
  2. Use the concept of arraylist so that you can dynamicaly increase the limit for your number of car. i this particular code you use only 20 cars.
  • This does not answer the actual question in any way, even though yours points could be valid, but an answer. I would suggest you ask better questions or answer some other questions to gain the reputation for commenting on posts. – YoungHobbit Jan 06 '16 at 16:51
  • @Akhi Youngisthan I have the option of doing the advanced way, but I am so far going for a simple version. Also the array list is not a bad idea as I would need more than 20 cars. – collision934 Jan 06 '16 at 17:04