Update OOP/Java/Assignments/FISAC/Q10.java
This commit is contained in:
		
							parent
							
								
									54711066ac
								
							
						
					
					
						commit
						00b4a8e37c
					
				
					 1 changed files with 10 additions and 24 deletions
				
			
		| 
						 | 
				
			
			@ -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 {
 | 
			
		||||
            if (count == items.length) throw new FullException("Box is full");
 | 
			
		||||
            while (count == items.length) notFull.await();
 | 
			
		||||
            items[count++] = item;
 | 
			
		||||
            notEmpty.signal();
 | 
			
		||||
        } finally {
 | 
			
		||||
            lock.unlock();
 | 
			
		||||
        }
 | 
			
		||||
    synchronized void add(T item) throws FullException, InterruptedException {
 | 
			
		||||
        if (count == items.length) throw new FullException("Box is full");
 | 
			
		||||
        while (count == items.length) wait();
 | 
			
		||||
        items[count++] = item;
 | 
			
		||||
        notifyAll();
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    T retrieve() throws InterruptedException {
 | 
			
		||||
        lock.lock();
 | 
			
		||||
        try {
 | 
			
		||||
            while (count == 0) notEmpty.await();
 | 
			
		||||
            T item = items[--count];
 | 
			
		||||
            notFull.signal();
 | 
			
		||||
            return item;
 | 
			
		||||
        } finally {
 | 
			
		||||
            lock.unlock();
 | 
			
		||||
        }
 | 
			
		||||
    synchronized T retrieve() throws InterruptedException {
 | 
			
		||||
        while (count == 0) wait();
 | 
			
		||||
        T item = items[--count];
 | 
			
		||||
        notifyAll();
 | 
			
		||||
        return item;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    boolean isEmpty() {
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
		Loading…
	
	Add table
		Add a link
		
	
		Reference in a new issue