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..b24cc150 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,65 @@ package hse.java.lectures.lecture6.tasks.queue; -public class BoundedBlockingQueue { +import java.util.LinkedList; +import java.util.Queue; +public class BoundedBlockingQueue { + private final Queue q = new LinkedList(); + private int size = 0; + private final int capacity; + private final Object monitor; public BoundedBlockingQueue(int capacity) { - + if (capacity > 0) { + this.capacity = capacity; + monitor = new Object(); + } else { + throw new IllegalArgumentException("Capacity is zero"); + } } - public void put(T item) { - + public void put(T item) throws InterruptedException { + if (item == null) { + throw new NullPointerException("Item is null"); + } + synchronized (monitor) { + while (size == capacity) { + try { + monitor.wait(); + } catch (InterruptedException e) { + throw e; + } + } + q.add(item); + size++; + monitor.notifyAll(); + } } - public T take() { - return null; + public T take() throws InterruptedException { + synchronized (monitor) { + while (size == 0) { + try { + monitor.wait(); + } catch (InterruptedException e) { + throw e; + } + } + T value = q.remove(); + size--; + monitor.notifyAll(); + return value; + } } public int size() { - return 0; + synchronized (monitor) { + monitor.notify(); + return size; + } } public int capacity() { - return 0; + return capacity; } }