diff --git a/src/main/java/hse/java/lectures/lecture6/tasks/queue/BoundedBlockingQueue.java b/src/main/java/hse/java/lectures/lecture6/tasks/queue/BoundedBlockingQueue.java index 5c686cff..e5de52ae 100644 --- a/src/main/java/hse/java/lectures/lecture6/tasks/queue/BoundedBlockingQueue.java +++ b/src/main/java/hse/java/lectures/lecture6/tasks/queue/BoundedBlockingQueue.java @@ -1,25 +1,57 @@ package hse.java.lectures.lecture6.tasks.queue; +import java.util.LinkedList; + public class BoundedBlockingQueue { + final Integer capacity ; + LinkedList list; + Object monitor ; public BoundedBlockingQueue(int capacity) { + if ( capacity <= 0 ) { + throw new IllegalArgumentException() ; + } + this.capacity = capacity; + list = new LinkedList<>(); + monitor = new Object(); + } - public void put(T item) { + public void put(T item) throws InterruptedException { + if ( item == null) throw new IllegalArgumentException() ; + + + synchronized (monitor) { + while ( capacity == list.size()) { + monitor.wait(); + } + list.add(item) ; + monitor.notifyAll(); + } } - public T take() { - return null; + public T take() throws InterruptedException { + synchronized (monitor) { + while (list.isEmpty()) { + monitor.wait(); + } + T res = list.removeFirst(); + monitor.notifyAll(); + return res; + } } public int size() { - return 0; + synchronized (monitor) { + return list.size(); + } } public int capacity() { - return 0; + return capacity; + } }