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..609a2698 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 @@ -2,24 +2,67 @@ public class BoundedBlockingQueue { + private final Object[] array; + int capacity; + int tail; + int head; + int fill; + public BoundedBlockingQueue(int capacity) { + if (capacity <= 0) { + throw new IllegalArgumentException(); + } + this.array = new Object[capacity]; + this.capacity = capacity; + this.head = 0; + this.tail = 0; + this.fill = 0; } - public void put(T item) { + public void put(T item) throws InterruptedException { + if (item == null) { + throw new NullPointerException(); + } + synchronized (this) { + while (fill == capacity) { + this.wait(); + } + array[tail] = item; + tail = (tail + 1) % capacity; + fill++; + this.notifyAll(); + + } } - public T take() { - return null; + public T take() throws InterruptedException { + synchronized (this) { + while (fill == 0) { + wait(); + } + + T item = (T) array[head]; + array[head] = null; + head = (head + 1) % capacity; + fill--; + + this.notifyAll(); + return item; + + } + + } public int size() { - return 0; + return fill; } public int capacity() { - return 0; + + return capacity; } }