Add OOP/Java/Assignments/FISAC/Q6.java
This commit is contained in:
parent
b15203dcf3
commit
ea7338aa75
34
OOP/Java/Assignments/FISAC/Q6.java
Normal file
34
OOP/Java/Assignments/FISAC/Q6.java
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user