MIT-Curricular/OOP/Java/Assignments/FISAC/Q6.java

35 lines
901 B
Java

class QueueFullException extends RuntimeException {}
class QueueEmptyException extends RuntimeException {}
class ThreadSafeQueue<T> {
private final Object lock = new Object();
private final T[] queue;
private int size = 0;
private int front = 0;
private int rear = 0;
@SuppressWarnings("unchecked")
public ThreadSafeQueue() {
queue = (T[]) new Object[10];
}
public void enqueue(T item) {
synchronized (lock) {
if (size >= 10) throw new QueueFullException();
queue[rear] = item;
rear = (rear + 1) % queue.length;
size++;
}
}
public T dequeue() {
synchronized (lock) {
if (size == 0) throw new QueueEmptyException();
T item = queue[front];
front = (front + 1) % queue.length;
size--;
return item;
}
}
}