Add OOP/Java/Assignments/FISAC/Q6.java

This commit is contained in:
Aadit Agrawal 2024-10-28 01:07:05 +05:30
parent b15203dcf3
commit ea7338aa75

View File

@ -0,0 +1,34 @@
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;
}
}
}