53 lines
1.4 KiB
Java
53 lines
1.4 KiB
Java
package semaphore;
|
|
|
|
import java.util.List;
|
|
import java.util.ArrayList;
|
|
import java.util.concurrent.Semaphore;
|
|
|
|
public class ValetQueue implements Queue<Car> {
|
|
private final List<Car> waitingCars;
|
|
private final int queueMaxSize;
|
|
private final Semaphore full, empty, mutex;
|
|
private int firstFree = 0, firstFull = 0;
|
|
|
|
public ValetQueue(int queueMaxSize) {
|
|
this.queueMaxSize = queueMaxSize;
|
|
waitingCars = new ArrayList<>(this.queueMaxSize);
|
|
|
|
for (int i = 0; i < queueMaxSize; i++) {
|
|
waitingCars.add(null);
|
|
}
|
|
|
|
empty = new Semaphore (this.queueMaxSize);
|
|
full = new Semaphore(0);
|
|
mutex = new Semaphore(1);
|
|
}
|
|
|
|
@Override
|
|
public void put(Car element) throws InterruptedException {
|
|
empty.acquire();
|
|
mutex.acquire();
|
|
waitingCars.set(firstFree, element);
|
|
firstFree = (firstFree + 1) % queueMaxSize;
|
|
System.out.println("Car with plate " + element.getPlate() + " in queue");
|
|
System.out.println("Now waiting: " + waitingCars);
|
|
mutex.release();
|
|
full.release();
|
|
}
|
|
|
|
@Override
|
|
public Car take() throws InterruptedException {
|
|
final Car c;
|
|
full.acquire();
|
|
mutex.acquire();
|
|
c = waitingCars.get(this.firstFull);
|
|
waitingCars.set(this.firstFull, null);
|
|
firstFull = (firstFull + 1) % queueMaxSize;
|
|
System.out.println("Car with plate " + c.getPlate() + " will be parked now");
|
|
System.out.println("Now waiting: " + waitingCars);
|
|
mutex.release();
|
|
empty.release();
|
|
return c;
|
|
}
|
|
}
|