43 lines
1.1 KiB
Java
43 lines
1.1 KiB
Java
package implicit;
|
|
|
|
import semaphore.Car;
|
|
import semaphore.Queue;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
import java.util.concurrent.Semaphore;
|
|
|
|
public class ImplicitValetQueue implements Queue<Car> {
|
|
private final List<Car> waitingCars;
|
|
private final int queueMaxSize;
|
|
|
|
public ImplicitValetQueue(int queueMaxSize) {
|
|
this.queueMaxSize = queueMaxSize;
|
|
waitingCars = new ArrayList<>(this.queueMaxSize);
|
|
}
|
|
|
|
@Override
|
|
public synchronized void put(Car element) throws InterruptedException {
|
|
while (waitingCars.size() >= queueMaxSize) {
|
|
wait();
|
|
}
|
|
|
|
waitingCars.add(element);
|
|
System.out.println("Car with plate " + element.getPlate() + " in queue");
|
|
System.out.println("Now waiting: " + waitingCars);
|
|
notifyAll();
|
|
}
|
|
|
|
@Override
|
|
public synchronized Car take() throws InterruptedException {
|
|
while (waitingCars.isEmpty()) {
|
|
wait();
|
|
}
|
|
Car c = waitingCars.remove(waitingCars.size() - 1);
|
|
System.out.println("Car with plate " + c.getPlate() + " will be parked now");
|
|
System.out.println("Now waiting: " + waitingCars);
|
|
notifyAll();
|
|
return c;
|
|
}
|
|
}
|