Update OOP/Java/Assignments/FISAC/Q10.java
This commit is contained in:
parent
54711066ac
commit
00b4a8e37c
@ -1,5 +1,3 @@
|
|||||||
import java.util.concurrent.locks.*;
|
|
||||||
|
|
||||||
class FullException extends Exception {
|
class FullException extends Exception {
|
||||||
FullException(String msg) { super(msg); }
|
FullException(String msg) { super(msg); }
|
||||||
}
|
}
|
||||||
@ -7,31 +5,19 @@ class FullException extends Exception {
|
|||||||
class Box<T> {
|
class Box<T> {
|
||||||
private T[] items = (T[]) new Object[3];
|
private T[] items = (T[]) new Object[3];
|
||||||
private int count = 0;
|
private int count = 0;
|
||||||
private Lock lock = new ReentrantLock();
|
|
||||||
private Condition notFull = lock.newCondition(), notEmpty = lock.newCondition();
|
|
||||||
|
|
||||||
void add(T item) throws FullException, InterruptedException {
|
synchronized void add(T item) throws FullException, InterruptedException {
|
||||||
lock.lock();
|
if (count == items.length) throw new FullException("Box is full");
|
||||||
try {
|
while (count == items.length) wait();
|
||||||
if (count == items.length) throw new FullException("Box is full");
|
items[count++] = item;
|
||||||
while (count == items.length) notFull.await();
|
notifyAll();
|
||||||
items[count++] = item;
|
|
||||||
notEmpty.signal();
|
|
||||||
} finally {
|
|
||||||
lock.unlock();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
T retrieve() throws InterruptedException {
|
synchronized T retrieve() throws InterruptedException {
|
||||||
lock.lock();
|
while (count == 0) wait();
|
||||||
try {
|
T item = items[--count];
|
||||||
while (count == 0) notEmpty.await();
|
notifyAll();
|
||||||
T item = items[--count];
|
return item;
|
||||||
notFull.signal();
|
|
||||||
return item;
|
|
||||||
} finally {
|
|
||||||
lock.unlock();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
boolean isEmpty() {
|
boolean isEmpty() {
|
||||||
|
Loading…
Reference in New Issue
Block a user