Update OOP/Java/Assignments/FISAC/Q10.java

This commit is contained in:
Aadit Agrawal 2024-10-28 03:06:19 +05:30
parent 54711066ac
commit 00b4a8e37c

View File

@ -1,5 +1,3 @@
import java.util.concurrent.locks.*;
class FullException extends Exception {
FullException(String msg) { super(msg); }
}
@ -7,31 +5,19 @@ class FullException extends Exception {
class Box<T> {
private T[] items = (T[]) new Object[3];
private int count = 0;
private Lock lock = new ReentrantLock();
private Condition notFull = lock.newCondition(), notEmpty = lock.newCondition();
void add(T item) throws FullException, InterruptedException {
lock.lock();
try {
synchronized void add(T item) throws FullException, InterruptedException {
if (count == items.length) throw new FullException("Box is full");
while (count == items.length) notFull.await();
while (count == items.length) wait();
items[count++] = item;
notEmpty.signal();
} finally {
lock.unlock();
}
notifyAll();
}
T retrieve() throws InterruptedException {
lock.lock();
try {
while (count == 0) notEmpty.await();
synchronized T retrieve() throws InterruptedException {
while (count == 0) wait();
T item = items[--count];
notFull.signal();
notifyAll();
return item;
} finally {
lock.unlock();
}
}
boolean isEmpty() {