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/explicit/ExplicitValetQueue.java

65 lines
1.5 KiB
Java

package explicit;
import semaphore.Car;
import semaphore.Queue;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class ExplicitValetQueue implements Queue<Car> {
private final List<Car> waitingCars;
private final int queueMaxSize;
private final ReentrantLock lock;
private final Condition full, empty;
public ExplicitValetQueue(int queueMaxSize) {
this.queueMaxSize = queueMaxSize;
waitingCars = new ArrayList<>(this.queueMaxSize);
lock = new ReentrantLock();
full = lock.newCondition();
empty = lock.newCondition();
}
@Override
public void put(Car element) throws InterruptedException {
lock.lock();
try {
while (waitingCars.size() >= this.queueMaxSize) {
full.await();
}
waitingCars.add(element);
System.out.println("Car with plate " + element.getPlate() + " in queue");
System.out.println("Now waiting: " + waitingCars);
empty.signal();
} finally {
lock.unlock();
}
}
@Override
public Car take() throws InterruptedException {
final Car c;
lock.lock();
try {
while (waitingCars.isEmpty()) {
empty.await();
}
c = waitingCars.remove(waitingCars.size() - 1);
System.out.println("Car with plate " + c.getPlate() + " will be parked now");
System.out.println("Now waiting: " + waitingCars);
full.signal();
} finally {
lock.unlock();
}
return c;
}
}