我正在用Java创建一个 parking 场,我有一个入口和一个导出。 parking 场有20个车位,我想我已经正确编码了入口/导出,有人要求我使用线程。

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();
    }
}

我只是停留在如何表示实际的 parking 库本身以及创建可以随着汽车驶近或驶离而增加或减少的空间上。到目前为止,我已经为主要方法编写了以下代码:
public static void main(String[] args){
    CarPark parkingGarage = new CarPark(20); //20 spaces
}

同样,当空间已满时,汽车需要排队等候一个空间,我认为最好将其表示为整数。
您可能会假设汽车无法同时进出(即系统会阻止这种情况由于锁定而发生)

最终,我需要将其放入客户端-服务器系统中。

任何建议,不胜感激!

最佳答案

我的观点是每个线程都应该代表一辆汽车。所以我会让主线程陷入循环:

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

每个汽车线程将类似于:
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");

09-30 18:40