This repository has been archived on 2021-10-31. You can view files and clone it, but cannot push or open issues or pull requests.
PF3/hw1/Ex2/src/implicit/ImplicitValetQueue.java

55 lines
1.3 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;
private int firstFree = 0, firstFull = 0, nElements = 0;
public ImplicitValetQueue(int queueMaxSize) {
this.queueMaxSize = queueMaxSize;
waitingCars = new ArrayList<>(this.queueMaxSize);
for (int i = 0; i < queueMaxSize; i++) {
waitingCars.add(null);
}
}
@Override
public synchronized void put(Car element) throws InterruptedException {
while (nElements == queueMaxSize) {
wait();
}
waitingCars.set(firstFree, element);
firstFree = (firstFree + 1) % queueMaxSize;
nElements++;
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 (nElements == 0) {
wait();
}
final Car c = waitingCars.get(this.firstFull);
waitingCars.set(this.firstFull, null);
firstFull = (firstFull + 1) % queueMaxSize;
nElements--;
System.out.println("Car with plate " + c.getPlate() + " will be parked now");
System.out.println("Now waiting: " + waitingCars);
notifyAll();
return c;
}
}